From a333f90d82a8b7b4b1d843cdd21b315136a8e403 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 15:15:35 +0200 Subject: [PATCH 01/20] Correct the polymorphic JSON format and grammar location in CLAUDE.md. Polymorphic values are written as a two-element array [typeId, {fields}], and only in hierarchies with an abstract root; a concrete root carries no type information. The grammar lives next to the generated parser in src/main/java, and the regenerated parser sources are checked in. Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f5276c1b..6b2ade22 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Key source locations: - Generator entry point: `de.haumacher.msgbuf.generator.Generator` - Code generators: `de.haumacher.msgbuf.generator.MessageGenerator`, `EnumGenerator` - Other targets: Dart (`generator.dart.DartLibGenerator`, `option DartLib`), TypeScript types (`generator.ts.TypeScriptGenerator`, `-ts ` / Maven `typeScriptOutputDirectory` / `option TypeScript`; golden-file test `TestTypeScriptGenerator`, update expected files with `-Dmsgbuf.ts.update=true`) -- JavaCC grammar: `de.haumacher.msgbuf.generator/src/main/javacc/protobuf.jj` +- JavaCC grammar: `de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/parser/protobuf.jj` (next to the generated parser sources) - AST proto definition: `de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto` ## Runtime API Architecture @@ -85,7 +85,7 @@ Extensions beyond standard protobuf: - **Self-bootstrapping**: Changes to `generator/ast/proto.proto` require regenerating the AST Java classes with an existing generator, then rebuilding. Maven reactor handles this automatically. - **NoInterfaces mode**: When set, generates single classes instead of interface + impl. Changes package structure (no `impl` subpackage). Many conditionals in `MessageGenerator` depend on this flag. -- **Polymorphic JSON**: Abstract types serialize as `[type, ...fields]` arrays. Concrete types in hierarchies use same format. Monomorphic references use `writeContent()` without type info. +- **Polymorphic JSON**: In a hierarchy with an abstract root, a value is written as a two-element array `[typeId, {fields}]` (the root's final `writeTo()`). A field declared with a concrete type of such a hierarchy uses `writeContent()` and writes the plain object without type info. A hierarchy with a concrete root carries no type info at all. - **Field IDs**: Auto-synthesis starts at 1, skips manually assigned IDs, is inheritance-aware (child fields can't clash with parent IDs). Field ID 0 is reserved. - **Tests use JUnit 3 style** (`extends TestCase`) despite JUnit 4 dependency. Tests exercise generated code, not the generator itself directly. - **GWT constraint**: No Java I/O classes in `msgbuf-api`. No Java 8+ features in generated code. @@ -105,5 +105,5 @@ Maven plugin integration tests: `msgbuf-generator-maven-plugin/src/it/` - Java 11+ required (`maven.compiler.source/target = 11`) - Generated code must be GWT-compatible (no `java.io` usage in `msgbuf-api`) -- Generator uses JavaCC — regenerate parser after grammar changes to `protobuf.jj` +- Generator uses JavaCC — the `javacc-maven-plugin` regenerates the parser into `src/main/java` during the build after grammar changes to `protobuf.jj`; the generated parser sources are checked in and must be committed with the grammar change - Different licenses: API is Apache-2.0, Generator is GPL-3.0-or-later (generated code is not GPL-encumbered) From b3d631d28e38378613f7ab5f422bc0847a3e4e76 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 15:15:35 +0200 Subject: [PATCH 02/20] Add the msgbuf-workflow skill for Claude Code sessions. Adapted from the VAlbum2 working method: issue intake, reproducing with a .proto first, agent briefs, probe reviews across inheritance, nesting, cross-file extension and the option matrix, and a verification gate that treats the checked-in generated test sources and the TypeScript outputs as golden files. Records the wire-format doctrines and the traps found while building the TypeScript target. Co-Authored-By: Claude Opus 5.5 (1M context) --- .claude/skills/msgbuf-workflow/SKILL.md | 248 ++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 .claude/skills/msgbuf-workflow/SKILL.md diff --git a/.claude/skills/msgbuf-workflow/SKILL.md b/.claude/skills/msgbuf-workflow/SKILL.md new file mode 100644 index 00000000..fbe92bfd --- /dev/null +++ b/.claude/skills/msgbuf-workflow/SKILL.md @@ -0,0 +1,248 @@ +--- +name: msgbuf-workflow +description: The working method for developing msgbuf — issue intake and triage, reproducing with a .proto first, sub-agent briefs, adversarial probe reviews composing generator features, the verification gate (Maven build, regenerated test sources as golden files, TypeScript golden files and tsc), branch/PR/commit discipline, and the wire-format and generated-code doctrines. Load at the start of any session doing feature or bug work on this repository. +--- + +# The msgbuf working method + +This skill is the meta-knowledge of how a session on this repository should run. It complements, +never duplicates, `CLAUDE.md` (build facts, architecture, gotchas) and `README.md` (the public +documentation of the `.proto` syntax, options and targets). Read both first. The GitHub issue +tracker at `msgbuf/msgbuf` **is** the work queue; `CHANGELOG.md` is the record of what shipped. + +## 1. The operating loop + +Work is a pipeline, not a pile: + +1. **Intake**: user reports (chat or GitHub issues) and the open issues at `msgbuf/msgbuf` + (`gh issue list -R msgbuf/msgbuf`). Bugs outrank queued features; a generator crash or + uncompilable generated code outranks everything. Triage every new issue with a diagnosis + comment *before* fixing. Labels are the GitHub defaults (`bug`, `enhancement`, `documentation`, …). +2. **Reproduce before dispatching.** Almost every report reduces to a `.proto` file. Write it, + run the built generator on it in a scratch directory, and compile or run the output: + + ```bash + J=$(ls $PWD/de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar) + java -jar $J -out /out /repro.proto # add -ts for the TypeScript target + ``` + + Know whether the problem is in the parser, the resolution/specialization stage, ID synthesis or + one code generator (§ "Generator Pipeline" in CLAUDE.md), and whether it is a real bug, an + already-fixed one, or your own probe error before an agent burns tokens. If the main tree is + agent-owned, reproduce in a git worktree (`git worktree add --detach /repro main`), + never in the live tree. +3. **Dispatch** one sub-agent per coherent package (§2), or do it yourself when the package is + small. msgbuf has one toolchain and one reactor, so parallel work needs separate worktrees (§3). +4. **Review with a novel probe** (§4). Non-negotiable. +5. **Gate** (§5), **commit and open or update the PR** (§6), close the issue with the fixing + commit or PR plus a summary comment naming the regression test. +6. **Before finishing: `gh issue list -R msgbuf/msgbuf`.** Anything you find and defer becomes an + issue (like #16–#21, found while building the TypeScript target), so a crashed session loses + nothing. + +Track packages with TaskCreate/TaskUpdate; keep statuses honest (in_progress on dispatch, +completed only after the commit is pushed). + +## 2. Agent briefs — what makes them work + +Use Opus for generator and runtime packages; Sonnet only for mechanical chores (regenerating, +README tables). Run in background; you'll be notified. A good brief contains, in order: + +- **Grounding**: "Read CLAUDE.md and README.md. Study ." Name the module + (`de.haumacher.msgbuf` runtime, `de.haumacher.msgbuf.generator`, the Maven plugin) and whether + `ast/proto.proto` or `parser/protobuf.jj` is in scope — both have regeneration consequences (§5). +- **The task as design intent**, with the load-bearing decisions already made: what the wire + format carries, what the generated API looks like, which options (`NoInterfaces`, `NoJson`, + `SharedGraph`, …) the change must respect, what the generator rejects with an error instead of + emitting broken code. Quote the user's own words where they designed the feature. +- **User fixtures embedded verbatim**: the `.proto` from the report, the JSON the user expects, the + compiler error they got. They become the regression test. +- **Explicit acceptance tests**: which test package under `src/test/java/test/` gets the new + `.proto` and the JUnit 3 test (`extends TestCase`, see CLAUDE.md); JSON/binary/XML round-trips + (write → read → equal) for every format the options leave enabled; exact expected JSON strings + where the format is the point. +- **The build discipline block** (the point is not wasting runs, not avoiding them): + - The edit loop runs the **owning module's targeted test**: + `mvn -q -pl de.haumacher.msgbuf.generator -am test -Dtest=TestHierarchy -Dsurefire.failIfNoSpecifiedTests=false`. + `-am` is needed unless the current `msgbuf-api` SNAPSHOT is installed in `~/.m2`. + - A generator change is not tested until the checked-in test sources are regenerated (§5) — + they are compiled from the repository, not generated by the build. + - The full `mvn clean install` runs at the end, before the report. A run whose inputs did not + change is not repeated "to be sure". Batch independent lookups in one call. +- **The standing rules block**: ALL existing tests green; never hand-edit generated code + (regenerate it: test sources, the AST classes from `proto.proto`, the JavaCC parser); + generated code and `msgbuf-api` stay GWT-compatible (no `java.io` Reader/Writer, Java language + level of the root pom); do NOT commit; **nothing half-done — cut whole items only and report + every cut**; a new generator error message names the file, the definition and the fix. +- **Ask for a report**: mechanism chosen and why, alternatives rejected, cuts, which checked-in + generated files changed and why, test count before/after. A vague report predicts a vague delivery. + +**Reworks go back to the same agent** via SendMessage with the failing probe and the demand: +*fix it generally, not to the probe*. If several rework rounds fail, question the architecture, +not the tests. + +**Stalled agents**: if a background agent's transcript goes quiet, check for a running `mvn` or +`java` process first (a long build is not a stall), then nudge-resume via SendMessage ("Resume +exactly where you left off: "). If it stays frozen, take the remainder over; +its uncommitted work is usually further along than its last message suggests (`git status`, run +its tests before redoing anything). + +**Crash recovery**: the crashed session's transcript is +`~/.claude/projects/-home-haui-devel-msgbuf/.jsonl`, sub-agent transcripts are in +`/subagents/`. Pull the last `Agent` tool_use out of the session transcript (that is the +brief, verbatim), check the tree (`git status`, `mvn -q compile`), and re-dispatch with a resume +preamble stating what exists and what compiles. Check `gh issue list` — reports filed during the +crash are untriaged. + +## 3. Concurrency — the rules + +- **Never let two agents edit the same file.** When parallelizing, write an explicit FILE BOUNDARY + paragraph into *both* briefs ("do not touch X, Y, Z; if you must, STOP and report"). +- **Shared hot spots have one owner per round**: `MessageGenerator.java` (most features touch it), + `ast/proto.proto` (regenerates the AST every generator class uses), `parser/protobuf.jj` + (regenerates the parser), and the checked-in test sources (a regeneration rewrites many files). +- **Concurrent Maven runs in one tree collide** on `target/` and on the `~/.m2` install of the + same SNAPSHOT. A second agent gets its own worktree (`git worktree add -b + /wt-x main`, run from this repo) and uses `mvn verify`, never `install`, so it cannot + overwrite the artifacts the main tree builds against. +- A commit made while an agent has uncommitted work in the tree must be **selective** + (`git add `). +- **A merge is not gated by the commits it merges.** Run the full gate (§5) on the merged tree — + generated code and generator changes are exactly where merges break. + +## 4. The probe review (the quality mechanism) + +After a delivery reports done and before committing: **write a `.proto` the agent never saw**, +composing the new feature with existing ones: inheritance three levels deep with an abstract +intermediate, nested messages and enums, cross-file `import` and `extends`, `@Nullable`, +`repeated` and `map` of the new construct, reserved-word names in backticks, and the option +matrix (`NoInterfaces`, `NoJson`/`NoBinary`/`NoXml`, `NoReflection`, `NoListener`, `NoVisitor`, +`SharedGraph`, `OpenWorld`). Generate, compile, round-trip. Good probes ask "is the mechanism +general?" not "does the happy path work?". Keep passing probes as permanent test packages. + +**Expect your own probes to be wrong first.** The traps seen so far: + +- **The generator derives its output root from the `package` declaration** when `-out` is missing: + the test protos live in `test//` but declare `package test..data;`, so running the jar on + them without `-out` writes a stray `src/test/test/` tree. Always pass `-out`. +- **A run with `-Dmsgbuf.ts.update=true` is not a test run** — it rewrites the TypeScript golden + files and then passes by construction. Rerun without the flag, and review the golden diff. +- **`mvn -pl de.haumacher.msgbuf.generator` alone fails to resolve `msgbuf-api:…-SNAPSHOT`** unless it + is installed — use `-am`, and then `-Dsurefire.failIfNoSpecifiedTests=false` with `-Dtest=…`. +- **Stale jar**: `target/msgbuf-generator-*-full.jar` is whatever the last `install`/`package` built, + possibly on another branch. Rebuild before probing a change. +- **A green unit build does not cover the plugin integration test**: `-Prun-its` runs it, and + `simple-it` is the archetype template calling a non-existent `touch` goal (#18) — it fails on + `main` too. Report it as known, don't chase it. +- **CLAUDE.md is not always right about the wire format**: polymorphic values are written as + `[typeId, {fields}]` (a two-element array whose second element is the object), and only when the + hierarchy root is abstract; references to a concrete type use `writeContent()` without a tag. + Check `MessageGenerator` (`writeTo`, `isMonomorphicReferenceToTypeInPolymorphicHierarchy`) + before asserting a format. +- **`gh pr view ` / `gh pr edit ` fail** with a GraphQL "Projects (classic) is being + deprecated" error. Use `gh pr view --json …` for reading and `gh api -X PATCH + repos/msgbuf/msgbuf/pulls/ -F body=@file` for editing. +- **`gh pr checkout` names the local branch differently** from the PR head, so a plain `git push` + is refused. Push with `git push origin HEAD:`. +- **A push can be rejected with a transient 403** ("Permission to msgbuf/msgbuf.git denied"). Report + it; on the user's request, retry once before suspecting credentials. +- **The Bash tool resets its working directory between calls.** Use absolute paths; never + `git add -A` after a relative `cd`. + +When a probe legitimately fails: send it back (§2). Small, deeper defects found on the way get +fixed with a regression test; unrelated ones become issues. Two classics to stay paranoid about: +generated code that does not compile for some option combination, and a silent change of the wire +format (§7). + +## 5. The verification gate (before every commit) + +```bash +mvn clean install # api → generator → plugin, all unit tests + +# If generator output changed: regenerate every checked-in test source and review the diff. +J=$(ls $PWD/de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar) # absolute, before the cd +cd de.haumacher.msgbuf.generator +for p in $(find src/test/java -name '*.proto'); do java -jar $J -out src/test/java $p; done +git status --short # every changed file must be explained by the change +cd .. && mvn clean install # the regenerated sources compile and pass +``` + +- **The checked-in generated test sources are golden files.** On `main`, regenerating them yields + zero diff. The loop prints `ERROR: Map types not supported in XML: …` (five times) and a + `Duplicate index '1' for 'RUNNING' and 'STARTED'` notice for the existing test protos — expected, + not a failure. After a generator change, the diff of `src/test/java/test/**` *is* the review of the + generated code: an unexplained change is a regression. +- **AST change** (`ast/proto.proto`): regenerate the AST classes with the previous generator + (`java -jar $J -out src/main/java src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto`), + then rebuild. The build does not do this for you (#23; CLAUDE.md still claims otherwise). +- **Grammar change** (`parser/protobuf.jj`, next to the parser sources): the JavaCC plugin + regenerates the parser into `src/main/java` during the build; the regenerated parser files are + checked in and ride the same commit. +- **TypeScript target**: `TestTypeScriptGenerator` compares against + `src/test/resources/ts/expected`; update with `-Dmsgbuf.ts.update=true`, then review the diff and + rerun without the flag. Type-check the golden files plus a usage file with `@ts-expect-error` + negative cases in the scratchpad: + `npx -y -p typescript tsc --strict --noEmit --isolatedModules --verbatimModuleSyntax --moduleResolution bundler --module esnext --target es2020 `. +- **Maven plugin changes**: also run `mvn install -Prun-its -pl msgbuf-generator-maven-plugin` + (known failure #18 until fixed). +- The Eclipse plugin (`de.haumacher.msgbuf.eclipse`, `de.haumacher.msgbuf.feature`) is not in + the reactor; changes there need a separate Eclipse/PDE build and are rare. + +All green or no commit. Never trust a green result from a tree with uncommitted foreign edits; +check `git status` first. When reporting, give the numbers (tests per module) and say what was +*not* run — the user asks. + +## 6. Branches, commits, PRs, releases + +- **Issue work goes through a branch and a PR** (`feature/issue--`, `fix/issue--` + in `msgbuf/msgbuf`, as for #12–#14), `Closes #` in the PR body. Small doc and chore fixes + may go straight to `main` when the user says so. External contributions arrive as PRs from forks. +- **House style**: an imperative one-line title stating the change, then a paragraph of the why + (never a bullet changelog), ending with the Co-Authored-By line from the harness rules. + Regenerated files ride the same commit as the change that produced them. +- **`CHANGELOG.md`**: every user-visible change gets an entry under the next version (the current + SNAPSHOT), in the existing sections (New Features, Bug Fixes). README documents every new + syntax element, option and generator switch. +- **PR descriptions** stay true to the branch: when a follow-up commit changes behavior, update the + description in the same step (§4 for the `gh` workaround). +- **The agents don't commit; you do**, after review. Pushing and force-pushing a shared branch are + the user's call; a history rewrite of a PR branch others may have checked out needs explicit consent. +- **Releases are the user's**: `mvn release:clean release:prepare` / `release:perform` + (HOWTO-RELEASE.md) publish to Maven Central. Never run them, never edit the version numbers the + release plugin manages. + +## 7. Wire-format and generated-code doctrines (enforce in every brief and review) + +- **The wire formats are a contract with deployed peers.** JSON, binary and XML written by one + msgbuf version are read by another (TopLogic servers and clients, Dart and TypeScript consumers). + A change in what a generated writer emits is a breaking change: it needs an explicit decision, + a README and CHANGELOG note, and readers that still accept the old form. Readers stay lenient + (missing properties take defaults). +- **All targets describe one format.** The Java writer is the reference; the Dart and TypeScript + targets must describe exactly what it writes (property names = `*__PROP` constants, enum + protocol names, nullable fields omitted, polymorphic tuples). Verify against the Java generator, + not against the docs. +- **Generated code must compile for every option combination** and stay GWT-compatible: no + `java.io` Reader/Writer in `msgbuf-api` or generated code, no features beyond the language level + of the root pom, no dependencies beyond `msgbuf-api`. +- **The generator rejects, it doesn't emit garbage.** Invalid input gets an error naming the + file and definition (see #16, #21 for the failure mode to avoid: a crash or uncompilable output). +- **Names are honest.** Generated and internal names say what a thing is (the TypeScript types are + `…Json` because they describe the JSON format, not the data). The user will notice a name that + claims more than it delivers. +- **Licenses**: `msgbuf-api` is Apache-2.0, the generator GPL-3.0-or-later, generated code is + unencumbered. Generated code may only depend on `msgbuf-api`; don't copy generator code into + templates of generated code. +- **Everything generic**: a fix shaped like the bug report is not done. It must hold for nested, + inherited, cross-file and option-varied variants of the reported case (the probe of §4). + +## 8. Working with this user + +The user is the author of msgbuf, an expert in Java, code generation and software architecture, +and a main downstream consumer (TopLogic). They review sharply and ask for evidence: "did you run +the tests???" is answered with the command, the counts per module, and what was not run — never +with an unqualified "yes". Their design remarks are usually complete (e.g. naming the generated +TypeScript types after what they are); restate the design crisply, adopt it, and credit it in the +commit message. Answer questions with the mechanism first, then the recommendation. When they +overrule a suggestion ("keep one PR"), follow it without relitigating. From a0fafc9a8ad79fcf25f75dc03b12eba822d6ba0b Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 15:27:11 +0200 Subject: [PATCH 03/20] Deploy releases to Maven Central from a GitHub workflow on tag push. Releasing required a local `release:perform` with the Central Portal token and the GPG key on the maintainer's machine. `release:prepare` already pushes the `msgbuf-api-` tag, so a workflow triggered by that tag now does the perform half. It checks the tag against the project version, builds and signs the tagged sources and deploys them through the central-publishing-maven-plugin. The credentials come from repository secrets. A manual run builds and signs without deploying, to check the secrets before the first release. maven-gpg-plugin 1.5 could not sign non-interactively, so it is upgraded to 3.2.7, which reads MAVEN_GPG_PASSPHRASE and still falls back to the gpg-agent for local releases. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/msgbuf-workflow/SKILL.md | 7 ++- .github/workflows/release.yml | 80 +++++++++++++++++++++++++ HOWTO-RELEASE.md | 38 ++++++++++-- pom.xml | 8 ++- 4 files changed, 121 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/release.yml diff --git a/.claude/skills/msgbuf-workflow/SKILL.md b/.claude/skills/msgbuf-workflow/SKILL.md index fbe92bfd..a55cdb48 100644 --- a/.claude/skills/msgbuf-workflow/SKILL.md +++ b/.claude/skills/msgbuf-workflow/SKILL.md @@ -208,9 +208,10 @@ check `git status` first. When reporting, give the numbers (tests per module) an description in the same step (§4 for the `gh` workaround). - **The agents don't commit; you do**, after review. Pushing and force-pushing a shared branch are the user's call; a history rewrite of a PR branch others may have checked out needs explicit consent. -- **Releases are the user's**: `mvn release:clean release:prepare` / `release:perform` - (HOWTO-RELEASE.md) publish to Maven Central. Never run them, never edit the version numbers the - release plugin manages. +- **Releases are the user's**: `mvn release:clean release:prepare` pushes a `msgbuf-api-` + tag, and the tag push runs `.github/workflows/release.yml`, which deploys to Maven Central + (HOWTO-RELEASE.md). Never run `release:*`, never push a `msgbuf-api-*` tag, never edit the + version numbers the release plugin manages. ## 7. Wire-format and generated-code doctrines (enforce in every brief and review) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..c05e4383 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,80 @@ +# Deploys a release to Maven Central when a release tag is pushed. +# +# The tag is created by `mvn release:clean release:prepare` (tag format msgbuf-api-, +# see tagNameFormat of the maven-release-plugin in pom.xml), which also pushes it. This workflow +# then builds the tagged sources, signs the artifacts and publishes them through the Central +# Portal (central-publishing-maven-plugin) - the part `mvn release:perform` did before. +# +# Required repository secrets: +# CENTRAL_USERNAME - user name of a Central Portal user token (https://central.sonatype.com/account) +# CENTRAL_PASSWORD - password of that user token +# GPG_PRIVATE_KEY - ASCII-armored secret signing key (gpg --armor --export-secret-keys ) +# GPG_PASSPHRASE - passphrase of that key +# +# A manual run (workflow_dispatch) builds and signs the current branch without deploying, +# to check the build and the signing secrets before cutting a release. + +name: Release to Maven Central + +on: + push: + tags: + - 'msgbuf-api-*' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + release: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - name: Check out + uses: actions/checkout@v5 + + - name: Set up JDK, Maven settings and signing key + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '21' + cache: maven + server-id: central + server-username: CENTRAL_USERNAME + server-password: CENTRAL_PASSWORD + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + + - name: Check that the tag matches the project version + if: github.event_name == 'push' + run: | + version=$(mvn -B -q -N help:evaluate -Dexpression=project.version -DforceStdout) + tag="${GITHUB_REF_NAME}" + echo "Tag: ${tag}, project version: ${version}" + if [ "${tag}" != "msgbuf-api-${version}" ]; then + echo "::error::Tag ${tag} does not match project version ${version} (expected msgbuf-api-${version})." + exit 1 + fi + case "${version}" in + *-SNAPSHOT) + echo "::error::Refusing to release snapshot version ${version}." + exit 1 + ;; + esac + + - name: Build and sign (dry run) + if: github.event_name != 'push' + run: mvn -B -Possrh clean verify + env: + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + + - name: Deploy to Maven Central + if: github.event_name == 'push' + run: mvn -B -Possrh clean deploy + env: + CENTRAL_USERNAME: ${{ secrets.CENTRAL_USERNAME }} + CENTRAL_PASSWORD: ${{ secrets.CENTRAL_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} diff --git a/HOWTO-RELEASE.md b/HOWTO-RELEASE.md index 060c13d9..f804cc66 100644 --- a/HOWTO-RELEASE.md +++ b/HOWTO-RELEASE.md @@ -6,18 +6,44 @@ mvn release:clean release:prepare ``` +This sets the release version, commits, creates the tag `msgbuf-api-`, sets the next +snapshot version, commits again and pushes both commits and the tag. + ## Release to Maven Central -``` -mvn release:perform -``` +Pushing the tag starts the GitHub workflow `.github/workflows/release.yml` ("Release to Maven +Central"). It checks that the tag matches the project version, builds the tagged sources, signs the +artifacts and publishes them through the Central Portal. It waits until the deployment is +published. Follow it in the repository's Actions tab. + +Do **not** run `mvn release:perform` in addition: the version would be deployed twice, and the +second deployment is rejected by Maven Central. +The workflow needs these repository secrets (Settings → Secrets and variables → Actions): + +| Secret | Content | +|--------------------|-------------------------------------------------------------------------| +| `CENTRAL_USERNAME` | User name of a Central Portal user token (central.sonatype.com → Account → Generate User Token) | +| `CENTRAL_PASSWORD` | Password of that user token | +| `GPG_PRIVATE_KEY` | ASCII-armored signing key: `gpg --armor --export-secret-keys ` | +| `GPG_PASSPHRASE` | Passphrase of that key | + +To check the build and the signing secrets without releasing, run the workflow manually (Actions → +Release to Maven Central → Run workflow): it builds and signs the selected branch but does not +deploy. + +A failed deployment can be repeated by re-running the workflow for the tag, as long as nothing was +published yet. ## Signing -Artifacts are GPG signed only in the `ossrh` profile. `release:perform` activates it automatically (see -`releaseProfiles` of the `maven-release-plugin`), so a regular `mvn install` does not require a GPG key. -For a manual deployment to Maven Central, activate the profile explicitly: +Artifacts are GPG signed only in the `ossrh` profile. The release workflow and `release:perform` +activate it, so a regular `mvn install` does not require a GPG key. The key passphrase is read from +the environment variable `MAVEN_GPG_PASSPHRASE` if set, otherwise the gpg-agent is asked. + +For a manual deployment to Maven Central (e.g. if GitHub Actions is unavailable), check out the +tag and activate the profile explicitly. This needs the `central` server credentials in +`~/.m2/settings.xml`: ``` mvn deploy -Possrh diff --git a/pom.xml b/pom.xml index 385d0512..39d659b6 100644 --- a/pom.xml +++ b/pom.xml @@ -140,8 +140,10 @@ ossrh @@ -151,7 +153,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.5 + 3.2.7 sign-artifacts From 301729826216186fc0e4c8342b6e39ebf805a10a Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 15:32:49 +0200 Subject: [PATCH 04/20] Resolve the defining file of nested definitions to fix polymorphic hierarchies nested in messages. Only top-level definitions have their file set, and `getFile() == null` marks a definition as nested for name qualification. The specialization and OpenWorld logic used `getFile()` to mean "the file this definition is declared in". So an abstract message nested in another message crashed the generator with a NullPointerException (#16), and the "same file" filter for local subtypes worked for nested definitions only by accident. `Util.definingFile()` walks up to the top-level definition and is now used at every such site; it replaces a private copy in the TypeScript generator. Probes found two more defects on the same path. JSON and XML readers of a top-level root referenced nested subtypes by their simple names, which did not compile. An extension file whose only extension of an OpenWorld root is nested did not get the implied NoBinary. Closes #16 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + .../generator/AbstractMessageGenerator.java | 4 +- .../msgbuf/generator/CodeConvention.java | 4 +- .../haumacher/msgbuf/generator/Generator.java | 27 +- .../msgbuf/generator/MessageGenerator.java | 6 +- .../msgbuf/generator/common/Util.java | 19 + .../generator/plugins/XmlStreamingPlugin.java | 4 +- .../generator/ts/TypeScriptGenerator.java | 21 +- .../src/test/java/test/nested/TestNested.java | 303 +++ .../test/java/test/nested/TestNestedDoc.java | 116 ++ .../test/java/test/nested/data/Animal.java | 92 + .../test/java/test/nested/data/Holder.java | 127 ++ .../test/java/test/nested/data/Level1.java | 471 +++++ .../src/test/java/test/nested/data/Outer.java | 357 ++++ .../test/java/test/nested/data/Triangle.java | 71 + .../src/test/java/test/nested/data/Zoo.java | 254 +++ .../test/nested/data/impl/Animal_Impl.java | 253 +++ .../test/nested/data/impl/Holder_Impl.java | 538 ++++++ .../test/nested/data/impl/Level1_Impl.java | 1682 +++++++++++++++++ .../test/nested/data/impl/Outer_Impl.java | 1301 +++++++++++++ .../test/nested/data/impl/Triangle_Impl.java | 246 +++ .../java/test/nested/data/impl/Zoo_Impl.java | 974 ++++++++++ .../src/test/java/test/nested/doc/Doc.java | 522 +++++ .../src/test/java/test/nested/doc/Figure.java | 64 + .../src/test/java/test/nested/doc/doc.proto | 32 + .../java/test/nested/doc/impl/Doc_Impl.java | 1640 ++++++++++++++++ .../test/nested/doc/impl/Figure_Impl.java | 217 +++ .../src/test/java/test/nested/note/Note.java | 144 ++ .../java/test/nested/note/impl/Note_Impl.java | 638 +++++++ .../src/test/java/test/nested/note/note.proto | 13 + .../test/java/test/nested/owbase/Events.java | 182 ++ .../test/nested/owbase/impl/Events_Impl.java | 658 +++++++ .../test/java/test/nested/owbase/owbase.proto | 19 + .../java/test/nested/owcount/CountEvent.java | 52 + .../test/nested/owcount/OwcountTypes.java | 19 + .../nested/owcount/impl/CountEvent_Impl.java | 181 ++ .../java/test/nested/owcount/owcount.proto | 8 + .../java/test/nested/owext/OwextTypes.java | 19 + .../test/java/test/nested/owext/Patches.java | 89 + .../test/nested/owext/impl/Patches_Impl.java | 306 +++ .../test/java/test/nested/owext/owext.proto | 17 + .../src/test/java/test/nested/shapes.proto | 100 + .../de.haumacher.msgbuf.data.TypeRegistration | 2 + 43 files changed, 11768 insertions(+), 31 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedDoc.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Animal.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Holder.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Level1.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Outer.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Triangle.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Zoo.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Animal_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Holder_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Level1_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Outer_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Triangle_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Zoo_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Doc.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Figure.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/doc.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Doc_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Figure_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/note/Note.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/note/impl/Note_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/note/note.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/owbase.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/CountEvent.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/impl/CountEvent_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/owcount.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/Patches.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/impl/Patches_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/owext.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/shapes.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 236509e0..0bc58689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ - **File documentation comment**: A doc comment before the `syntax` or `package` declaration is kept as the documentation of the `.proto` file (`DefinitionFile.comment`) and emitted as TSDoc `@packageDocumentation` of the TypeScript module. +### Bug Fixes +- **Nested polymorphic hierarchies** (#16): An abstract message nested in another message no longer crashes the + generator with a `NullPointerException`. Nested sub-messages of a top-level abstract message are referenced by + their qualified names in the generated JSON and XML readers (previously uncompilable). For `option OpenWorld`, the + "same file" test for local subtypes and the implied `NoBinary` of extension files now also hold for nested + definitions. + ## 1.2.1 ### Bug Fixes diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java index 2436e5ba..c9cd9723 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/AbstractMessageGenerator.java @@ -71,7 +71,7 @@ protected String qImplName(MessageDef def) { protected static List concreteSpecializations(MessageDef def) { ArrayList result = new ArrayList<>(); - addConcreteSpecializations(result, def, def.getFile()); + addConcreteSpecializations(result, def, Util.definingFile(def)); return result; } @@ -95,7 +95,7 @@ protected static List localSpecializations(MessageDef def, Definitio return def.getSpecializations(); } return def.getSpecializations().stream() - .filter(s -> s.getFile() == originFile) + .filter(s -> Util.definingFile(s) == originFile) .collect(Collectors.toList()); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java index 588fd329..46c6abe4 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java @@ -279,7 +279,9 @@ public static String jsonTypeConstant(MessageDef def) { } public static String jsonTypeConstantRef(MessageDef def) { - return typeName(def) + "." + jsonTypeConstant(def); + // A nested specialization is not in scope by its simple name in the code of its generalization. + String typeRef = def.getFile() == null ? qTypeName(def) : typeName(def); + return typeRef + "." + jsonTypeConstant(def); } public static String mkBinaryTypeConstant(MessageDef def) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index bac207a2..194879f4 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -312,17 +312,29 @@ private void propagateOpenWorldOptions(DefinitionFile file) { // Already an OpenWorld file, options already set return; } - for (Definition def : file.getDefinitions()) { + if (extendsOpenWorldFromOtherFile(file, file.getDefinitions())) { + // Extension file inherits NoBinary from OpenWorld base + file.getOptions().put("NoBinary", Flag.create().setValue(true)); + } + } + + private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, List definitions) { + for (Definition def : definitions) { if (def instanceof MessageDef) { MessageDef msg = (MessageDef) def; MessageDef extended = msg.getExtendedDef(); - if (extended != null && extended.getFile() != file && Util.getFlag(extended.getFile(), "OpenWorld")) { - // Extension file inherits NoBinary from OpenWorld base - file.getOptions().put("NoBinary", Flag.create().setValue(true)); - return; + if (extended != null) { + DefinitionFile extendedFile = Util.definingFile(extended); + if (extendedFile != file && Util.getFlag(extendedFile, "OpenWorld")) { + return true; + } + } + if (extendsOpenWorldFromOtherFile(file, msg.getDefinitions())) { + return true; } } } + return false; } private void resolveImports(DefinitionFile file, File sourceFile) throws IOException, ParseException { @@ -491,8 +503,9 @@ private List findCrossFileExtensions(DefinitionFile file) { private void collectCrossFileExtensions(MessageDef def, DefinitionFile file, List result) { MessageDef extended = def.getExtendedDef(); - if (extended != null && extended.getFile() != file) { - if (Util.getFlag(extended.getFile(), "OpenWorld")) { + DefinitionFile extendedFile = extended == null ? null : Util.definingFile(extended); + if (extendedFile != null && extendedFile != file) { + if (Util.getFlag(extendedFile, "OpenWorld")) { if (!def.isAbstract()) { result.add(def); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index d3d7abd4..853c60f6 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -17,6 +17,7 @@ import de.haumacher.msgbuf.binary.DataType; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; +import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MapType; @@ -2345,11 +2346,12 @@ private String getOpenWorldRoot() { private boolean isCrossFileExtension() { MessageDef gen = getAbstractGeneralization(); if (gen == null) return false; - return gen.getFile() != _def.getFile() && Util.getFlag(gen.getFile(), "OpenWorld"); + DefinitionFile genFile = Util.definingFile(gen); + return genFile != Util.definingFile(_def) && Util.getFlag(genFile, "OpenWorld"); } private List localSpecializations(MessageDef def) { - return localSpecializations(def, _def.getFile()); + return localSpecializations(def, Util.definingFile(_def)); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java index f2ace617..2f0da893 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java @@ -11,6 +11,7 @@ import de.haumacher.msgbuf.generator.CodeConvention; import de.haumacher.msgbuf.generator.ast.CustomType; import de.haumacher.msgbuf.generator.ast.Definition; +import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.Flag; @@ -45,6 +46,24 @@ public static String stringContent(String stringLiteral) { return stringLiteral.substring(1, stringLiteral.length() - 1).replaceAll("\\\\(.)", "$1"); } + /** + * The file the given definition is declared in. + * + *

+ * Only top-level definitions have a direct reference to their file ({@link Definition#getFile()} + * is null for nested definitions, which marks them as nested for name + * qualification). For a nested definition, the file of its top-level outer definition is + * returned. + *

+ */ + public static DefinitionFile definingFile(Definition def) { + Definition current = def; + while (current.getOuter() != null) { + current = current.getOuter(); + } + return current.getFile(); + } + public static String toString(Definition def) { MessageDef outer = def.getOuter(); if (outer == null) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index 29ab65c0..bac45eef 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -442,7 +442,9 @@ private void readPrimitiveXmlElement(Field field) { } String xmlTypeNameRef(MessageDef def) { - return implName(def) + "." + xmlTypeNameConstant(def); + // A nested specialization is not in scope by its simple name in the code of its generalization. + String implRef = def.getFile() == null ? qImplName(def) : implName(def); + return implRef + "." + xmlTypeNameConstant(def); } }; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java index 16bca762..83b71d09 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java @@ -534,7 +534,7 @@ private String polymorphicType(MessageDef def) { for (MessageDef specialization : Util.concreteTransitiveSpecializations(def)) { alternatives.add("[" + stringLiteral(MsgBufJsonProtocol.typeId(specialization)) + ", " + ref(specialization, def) + "]"); } - if (Util.getFlag(fileOf(root(def)), "OpenWorld")) { + if (Util.getFlag(Util.definingFile(root(def)), "OpenWorld")) { // Extension types from other modules. alternatives.add("[string, " + ref(def, def) + "]"); } @@ -633,13 +633,13 @@ private static String primitiveType(PrimitiveType.Kind kind) { */ private String ref(Definition target, Definition context) { List path = path(target); - return ref(fileOf(target), path, context); + return ref(Util.definingFile(target), path, context); } private String polymorphicRef(MessageDef target, Definition context) { List path = path(target); path.set(path.size() - 1, polymorphicName(target)); - return ref(fileOf(target), path, context); + return ref(Util.definingFile(target), path, context); } private String ref(DefinitionFile file, List path, Definition context) { @@ -698,21 +698,6 @@ private String importBinding(DefinitionFile file, String name) { return binding; } - /** - * The file containing the given definition. - * - *

- * Only top-level definitions have a direct reference to their file. - *

- */ - private static DefinitionFile fileOf(Definition def) { - Definition current = def; - while (current.getOuter() != null) { - current = current.getOuter(); - } - return current.getFile(); - } - private static List path(Definition def) { List result = new ArrayList<>(); for (Definition current = def; current != null; current = current.getOuter()) { diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java new file mode 100644 index 00000000..a9752731 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.nested; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import de.haumacher.msgbuf.binary.OctetDataReader; +import de.haumacher.msgbuf.binary.OctetDataWriter; +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import de.haumacher.msgbuf.xml.XmlSerializable; +import junit.framework.TestCase; +import test.nested.data.Animal; +import test.nested.data.Holder; +import test.nested.data.Level1; +import test.nested.data.Level1.Level2; +import test.nested.data.Outer; +import test.nested.data.Triangle; +import test.nested.data.Zoo; +import test.nested.owbase.Events; +import test.nested.owcount.CountEvent; +import test.nested.owext.Patches; + +/** + * Test case for polymorphic hierarchies whose abstract root (or parts of it) are nested messages (issue #16). + */ +@SuppressWarnings("javadoc") +public class TestNested extends TestCase { + + /** The shape of the issue report: an abstract root nested in a message. */ + public void testNestedAbstractRootJson() throws IOException { + Outer.Shape circle = Outer.Circle.create().setRadius(5).setName("c"); + assertEquals("[\"Circle\",{\"name\":\"c\",\"radius\":5}]", circle.toString()); + + Outer.Shape copy = Outer.Shape.readShape(json(circle.toString())); + assertTrue(copy instanceof Outer.Circle); + assertEquals(5, ((Outer.Circle) copy).getRadius()); + assertEquals("c", copy.getName()); + } + + public void testTopLevelExtendingNestedJson() throws IOException { + Outer.Shape triangle = Triangle.create().setBase(3).setHeight(4).setName("t"); + assertEquals("[\"Triangle\",{\"name\":\"t\",\"base\":3,\"height\":4}]", triangle.toString()); + assertTrue(Outer.Shape.readShape(json(triangle.toString())) instanceof Triangle); + } + + public void testFieldsInNestedSibling() throws IOException, XMLStreamException { + Outer.Drawing drawing = Outer.Drawing.create() + .setMain(Outer.Square.create().setSide(2).setName("main")) + .addShape(Outer.Circle.create().setRadius(1)) + .addShape(Triangle.create().setBase(7)) + .addShape(Outer.Square.create().setSide(9)); + assertEquals( + "{\"main\":[\"Square\",{\"name\":\"main\",\"side\":2}],\"shapes\":[" + + "[\"Circle\",{\"name\":\"\",\"radius\":1}]," + + "[\"Triangle\",{\"name\":\"\",\"base\":7,\"height\":0}]," + + "[\"Square\",{\"name\":\"\",\"side\":9}]]}", + drawing.toString()); + + String expected = drawing.toString(); + assertEquals(expected, Outer.Drawing.readDrawing(json(expected)).toString()); + assertEquals(expected, Outer.Drawing.readDrawing(binaryReader(binary(drawing))).toString()); + assertEquals(expected, Outer.Drawing.readDrawing(xmlReader(xml(drawing))).toString()); + + Outer.Drawing copy = Outer.Drawing.readDrawing(json(expected)); + assertTrue(copy.getMain() instanceof Outer.Square); + assertTrue(copy.getShapes().get(0) instanceof Outer.Circle); + assertTrue(copy.getShapes().get(1) instanceof Triangle); + assertTrue(copy.getShapes().get(2) instanceof Outer.Square); + } + + public void testFieldInOuter() throws IOException, XMLStreamException { + Outer outer = Outer.create().setShape(Outer.Circle.create().setRadius(42).setName("x")); + String expected = outer.toString(); + assertEquals("{\"shape\":[\"Circle\",{\"name\":\"x\",\"radius\":42}]}", expected); + assertEquals(expected, Outer.readOuter(json(expected)).toString()); + assertEquals(expected, Outer.readOuter(binaryReader(binary(outer))).toString()); + assertEquals(expected, Outer.readOuter(xmlReader(xml(outer))).toString()); + } + + /** Root abstract, abstract intermediate, concrete leaves; nested two levels deep. */ + public void testDeeplyNestedWithAbstractIntermediate() throws IOException, XMLStreamException { + Level1 value = Level1.create() + .setNode(Level2.Root.create().setTitle("r") + .addChildren(Level2.Leaf.create().setValue(1)) + .addChildren(Level2.Branch.create().setExpanded(true) + .addChildren(Level2.Leaf.create().setValue(2).setLabel("deep")))) + .addNodes(Level2.Leaf.create().setValue(3)) + .addNodes(Level2.Branch.create()); + + String expected = value.toString(); + assertEquals( + "{\"node\":[\"Root\",{\"label\":\"\",\"children\":[" + + "[\"Leaf\",{\"label\":\"\",\"value\":1}]," + + "[\"Branch\",{\"label\":\"\",\"children\":[[\"Leaf\",{\"label\":\"deep\",\"value\":2}]],\"expanded\":true}]" + + "],\"title\":\"r\"}],\"nodes\":[" + + "[\"Leaf\",{\"label\":\"\",\"value\":3}]," + + "[\"Branch\",{\"label\":\"\",\"children\":[],\"expanded\":false}]]}", + expected); + assertEquals(expected, Level1.readLevel1(json(expected)).toString()); + assertEquals(expected, Level1.readLevel1(binaryReader(binary(value))).toString()); + assertEquals(expected, Level1.readLevel1(xmlReader(xml(value))).toString()); + + // Reading through the abstract intermediate. + Level2.Composite composite = Level2.Composite.readComposite(json(value.getNode().toString())); + assertTrue(composite instanceof Level2.Root); + assertEquals(2, composite.getChildren().size()); + } + + /** Nested sub-messages extending a top-level abstract root. */ + public void testNestedExtendingTopLevel() throws IOException, XMLStreamException { + Zoo zoo = Zoo.create() + .addAnimal(Zoo.Cat.create().setIndoor(true).setName("tom")) + .addAnimal(Zoo.Parrot.create().addWord("hello").setWingspan(0.5).setName("polly")); + + String expected = zoo.toString(); + assertEquals( + "{\"animals\":[[\"Cat\",{\"name\":\"tom\",\"indoor\":true}]," + + "[\"Parrot\",{\"name\":\"polly\",\"wingspan\":0.5,\"words\":[\"hello\"]}]]}", + expected); + assertEquals(expected, Zoo.readZoo(json(expected)).toString()); + assertEquals(expected, Zoo.readZoo(binaryReader(binary(zoo))).toString()); + assertEquals(expected, Zoo.readZoo(xmlReader(xml(zoo))).toString()); + + Animal parrot = Animal.readAnimal(json(zoo.getAnimals().get(1).toString())); + assertTrue(parrot instanceof Zoo.Parrot); + assertTrue(Zoo.Bird.readBird(json(parrot.toString())) instanceof Zoo.Parrot); + } + + /** A top-level message with fields of nested and top-level abstract types. */ + public void testTopLevelHolder() throws IOException, XMLStreamException { + Holder holder = Holder.create() + .setShape(Triangle.create().setHeight(1)) + .addShapes(Outer.Circle.create().setRadius(2)) + .addShapes(Outer.Square.create().setSide(3)) + .setNode(Level2.Leaf.create().setValue(4)) + .addAnimal(Zoo.Cat.create()); + + String expected = holder.toString(); + assertEquals(expected, Holder.readHolder(json(expected)).toString()); + assertEquals(expected, Holder.readHolder(binaryReader(binary(holder))).toString()); + assertEquals(expected, Holder.readHolder(xmlReader(xml(holder))).toString()); + + Holder copy = Holder.readHolder(binaryReader(binary(holder))); + assertTrue(copy.getShape() instanceof Triangle); + assertTrue(copy.getShapes().get(0) instanceof Outer.Circle); + assertTrue(copy.getShapes().get(1) instanceof Outer.Square); + assertTrue(copy.getNode() instanceof Level2.Leaf); + assertTrue(copy.getAnimals().get(0) instanceof Zoo.Cat); + } + + public void testVisitor() { + Outer.Shape.Visitor shapes = new Outer.Shape.Visitor<>() { + @Override + public String visit(Outer.Circle self, Void arg) { + return "circle"; + } + + @Override + public String visit(Outer.Square self, Void arg) { + return "square"; + } + + @Override + public String visit(Triangle self, Void arg) { + return "triangle"; + } + }; + assertEquals("circle", Outer.Circle.create().visit(shapes, null)); + assertEquals("square", Outer.Square.create().visit(shapes, null)); + assertEquals("triangle", Triangle.create().visit(shapes, null)); + + Level2.Node.Visitor nodes = new Level2.Node.Visitor<>() { + @Override + public String visit(Level2.Leaf self, Void arg) { + return "leaf"; + } + + @Override + public String visit(Level2.Branch self, Void arg) { + return "branch"; + } + + @Override + public String visit(Level2.Root self, Void arg) { + return "root"; + } + }; + assertEquals("leaf", Level2.Leaf.create().visit(nodes, null)); + assertEquals("branch", Level2.Branch.create().visit(nodes, null)); + assertEquals("root", Level2.Root.create().visit(nodes, null)); + // Dispatch through the abstract intermediate's visitor. + Level2.Node root = Level2.Root.create(); + assertEquals("root", ((Level2.Composite) root).visit((Level2.Composite.Visitor) nodes, null)); + + Animal.Visitor animals = new Animal.Visitor<>() { + @Override + public String visit(Zoo.Cat self, Void arg) { + return "cat"; + } + + @Override + public String visit(Zoo.Parrot self, Void arg) { + return "parrot"; + } + }; + assertEquals("cat", Zoo.Cat.create().visit(animals, null)); + assertEquals("parrot", Zoo.Parrot.create().visit(animals, null)); + } + + /** + * A nested OpenWorld root extended by nested and top-level messages of other files. + * + *

+ * OpenWorld implies NoBinary, so only JSON and XML apply. The extension types are discovered + * through the generated service descriptor in src/test/resources/META-INF/services. + * XML is checked for the local type only: the generated XML reader of an OpenWorld root does not + * consult the registry of extension types (for top-level roots neither). + *

+ */ + public void testOpenWorldCrossFile() throws IOException, XMLStreamException { + Events events = Events.create() + .addEvent(Events.TextEvent.create().setText("hi").setTimestamp(1)) + .addEvent(Patches.PatchEvent.create().setPatch("p").setTimestamp(2)) + .addEvent(CountEvent.create().setCount(3).setTimestamp(3)); + + String expected = events.toString(); + assertEquals( + "{\"events\":[[\"TextEvent\",{\"timestamp\":1,\"text\":\"hi\"}]," + + "[\"PatchEvent\",{\"timestamp\":2,\"patch\":\"p\"}]," + + "[\"CountEvent\",{\"timestamp\":3,\"count\":3}]]}", + expected); + + // OpenWorld implies NoBinary, also for a file whose only extension is nested. + assertFalse(Patches.PatchEvent.create() instanceof de.haumacher.msgbuf.binary.BinaryDataObject); + assertFalse(CountEvent.create() instanceof de.haumacher.msgbuf.binary.BinaryDataObject); + + Events copy = Events.readEvents(json(expected)); + assertEquals(expected, copy.toString()); + assertTrue(copy.getEvents().get(0) instanceof Events.TextEvent); + assertTrue(copy.getEvents().get(1) instanceof Patches.PatchEvent); + assertTrue(copy.getEvents().get(2) instanceof CountEvent); + + // XML: the local type of the base file is read back. + Events local = Events.create().addEvent(Events.TextEvent.create().setText("hi").setTimestamp(1)); + assertEquals(local.toString(), Events.readEvents(xmlReader(xml(local))).toString()); + + Events.Event.Visitor visitor = new Patches.PatchEvent.Visitor<>() { + @Override + public String visit(Events.TextEvent self, Void arg) { + return "text"; + } + + @Override + public String visit(Patches.PatchEvent self, Void arg) { + return "patch"; + } + + @Override + public String visitDefault(Events.Event self, Void arg) { + return "default"; + } + }; + assertEquals("text", copy.getEvents().get(0).visit(visitor, null)); + assertEquals("patch", copy.getEvents().get(1).visit(visitor, null)); + assertEquals("default", copy.getEvents().get(2).visit(visitor, null)); + } + + private static JsonReader json(String data) { + return new JsonReader(new StringR(data)); + } + + private static byte[] binary(de.haumacher.msgbuf.binary.BinaryDataObject value) throws IOException { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + value.writeTo(new OctetDataWriter(buffer)); + return buffer.toByteArray(); + } + + private static OctetDataReader binaryReader(byte[] data) { + return new OctetDataReader(new ByteArrayInputStream(data)); + } + + private static String xml(XmlSerializable value) throws XMLStreamException { + StringWriter buffer = new StringWriter(); + value.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + return buffer.toString(); + } + + private static XMLStreamReader xmlReader(String xml) throws XMLStreamException { + return XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedDoc.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedDoc.java new file mode 100644 index 00000000..d1e1bdbc --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedDoc.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.nested; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; + +import de.haumacher.msgbuf.binary.OctetDataReader; +import de.haumacher.msgbuf.binary.OctetDataWriter; +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import junit.framework.TestCase; +import test.nested.doc.Doc; +import test.nested.doc.Figure; +import test.nested.note.Note; + +/** + * Test case for a nested polymorphic hierarchy used in repeated, map and nullable fields, and + * referenced from another file (issue #16). + */ +@SuppressWarnings("javadoc") +public class TestNestedDoc extends TestCase { + + public void testJson() throws IOException { + Doc doc = createDoc(); + String json = doc.toString(); + assertEquals("{\"items\":[" + + "[\"Case\",{\"kind\":\"RICH\",\"package\":\"pkg\",\"weight\":3,\"children\":[" + + "[\"Para\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":1,\"text\":\"hello\"}]," + + "[\"Figure\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":0,\"src\":\"x.png\"}]," + + "[\"Case\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":0,\"children\":[]}]]}]," + + "[\"Figure\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":0,\"src\":\"y\"}]]," + + "\"byName\":{\"p\":[\"Para\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":0,\"text\":\"m\"}]}," + + "\"maybe\":[\"Figure\",{\"kind\":\"PLAIN\",\"package\":\"\",\"weight\":0,\"src\":\"\"}]}", json); + assertEquals(json, Doc.readDoc(new JsonReader(new StringR(json))).toString()); + } + + public void testJsonNullable() throws IOException { + String json = Doc.create().toString(); + assertEquals("{\"items\":[],\"byName\":{}}", json); + assertNull(Doc.readDoc(new JsonReader(new StringR(json))).getMaybe()); + } + + public void testBinary() throws IOException { + Doc doc = createDoc(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + doc.writeTo(new OctetDataWriter(buffer)); + Doc copy = Doc.readDoc(new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))); + assertEquals(doc.toString(), copy.toString()); + } + + public void testXml() throws XMLStreamException { + // Doc itself has a map field, which is not supported in XML. + Doc.Sec.Case value = createCase(); + StringWriter buffer = new StringWriter(); + value.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + Doc.Sec.Item copy = Doc.Sec.Item.readItem( + XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(buffer.toString()))); + assertEquals(value.toString(), copy.toString()); + } + + public void testCrossFileReference() throws IOException { + Note note = Note.create() + .setTarget(createCase()) + .setInner(Note.Inner.create().addRef(Figure.create()).addRef(Doc.Sec.Para.create())); + String json = note.toString(); + assertEquals(json, Note.readNote(new JsonReader(new StringR(json))).toString()); + } + + public void testVisitor() { + Doc.Sec.Item.Visitor visitor = + new Doc.Sec.Item.Visitor() { + @Override + public String visit(Doc.Sec.Para self, Void arg) { + return "para"; + } + + @Override + public String visit(Doc.Sec.Case self, Void arg) { + return "case"; + } + + @Override + public String visit(Figure self, Void arg) { + return "figure"; + } + }; + assertEquals("case", createCase().visit(visitor, null)); + assertEquals("figure", Figure.create().visit(visitor, null)); + } + + private static Doc createDoc() { + return Doc.create() + .addItem(createCase()) + .addItem(Figure.create().setSrc("y")) + .putByName("p", Doc.Sec.Para.create().setText("m")) + .setMaybe(Figure.create()); + } + + private static Doc.Sec.Case createCase() { + Doc.Sec.Case result = Doc.Sec.Case.create().setWeight(3).setPackage("pkg").setKind(Doc.Sec.Item.Kind.RICH); + result.addChildren(Doc.Sec.Para.create().setText("hello").setWeight(1)); + result.addChildren(Figure.create().setSrc("x.png")); + result.addChildren(Doc.Sec.Case.create()); + return result; + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Animal.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Animal.java new file mode 100644 index 00000000..319ca69d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Animal.java @@ -0,0 +1,92 @@ +package test.nested.data; + +/** + * A top-level abstract root. + */ +public interface Animal extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.data.Animal} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.data.Zoo.Cat}. */ + CAT, + + /** Type literal for {@link test.nested.data.Zoo.Parrot}. */ + PARROT, + ; + + } + + /** Visitor interface for the {@link test.nested.data.Animal} hierarchy.*/ + public interface Visitor extends test.nested.data.Zoo.Bird.Visitor { + + /** Visit case for {@link test.nested.data.Zoo.Cat}.*/ + R visit(test.nested.data.Zoo.Cat self, A arg) throws E; + + } + + /** @see #getName() */ + String NAME__PROP = "name"; + + /** Identifier for the property {@link #getName()} in binary format. */ + static final int NAME__ID = 1; + + /** The type code of this instance. */ + TypeKind kind(); + + String getName(); + + /** + * @see #getName() + */ + test.nested.data.Animal setName(String value); + + @Override + public test.nested.data.Animal registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Animal unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Animal readAnimal(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.Animal result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.data.Zoo.Cat.CAT__TYPE: result = test.nested.data.Zoo.Cat.readCat(in); break; + case test.nested.data.Zoo.Parrot.PARROT__TYPE: result = test.nested.data.Zoo.Parrot.readParrot(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** The binary identifier for this concrete type in the polymorphic {@link test.nested.data.Animal} hierarchy. */ + abstract int typeId(); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Animal readAnimal(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.data.Animal result; + switch (type) { + case test.nested.data.Zoo.Cat.CAT__TYPE_ID: result = test.nested.data.impl.Zoo_Impl.Cat_Impl.readCat_Content(in); break; + case test.nested.data.Zoo.Parrot.PARROT__TYPE_ID: result = test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Animal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Animal readAnimal(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Animal_Impl.readAnimal_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Holder.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Holder.java new file mode 100644 index 00000000..8deba0ef --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Holder.java @@ -0,0 +1,127 @@ +package test.nested.data; + +/** + * A top-level holder of values of nested abstract types. + */ +public interface Holder extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.nested.data.Holder} instance. + */ + static test.nested.data.Holder create() { + return new test.nested.data.impl.Holder_Impl(); + } + + /** Identifier for the {@link test.nested.data.Holder} type in JSON format. */ + String HOLDER__TYPE = "Holder"; + + /** @see #getShape() */ + String SHAPE__PROP = "shape"; + + /** @see #getShapes() */ + String SHAPES__PROP = "shapes"; + + /** @see #getNode() */ + String NODE__PROP = "node"; + + /** @see #getAnimals() */ + String ANIMALS__PROP = "animals"; + + /** Identifier for the property {@link #getShape()} in binary format. */ + static final int SHAPE__ID = 1; + + /** Identifier for the property {@link #getShapes()} in binary format. */ + static final int SHAPES__ID = 2; + + /** Identifier for the property {@link #getNode()} in binary format. */ + static final int NODE__ID = 3; + + /** Identifier for the property {@link #getAnimals()} in binary format. */ + static final int ANIMALS__ID = 4; + + test.nested.data.Outer.Shape getShape(); + + /** + * @see #getShape() + */ + test.nested.data.Holder setShape(test.nested.data.Outer.Shape value); + + /** + * Checks, whether {@link #getShape()} has a value. + */ + boolean hasShape(); + + java.util.List getShapes(); + + /** + * @see #getShapes() + */ + test.nested.data.Holder setShapes(java.util.List value); + + /** + * Adds a value to the {@link #getShapes()} list. + */ + test.nested.data.Holder addShapes(test.nested.data.Outer.Shape value); + + /** + * Removes a value from the {@link #getShapes()} list. + */ + void removeShapes(test.nested.data.Outer.Shape value); + + test.nested.data.Level1.Level2.Node getNode(); + + /** + * @see #getNode() + */ + test.nested.data.Holder setNode(test.nested.data.Level1.Level2.Node value); + + /** + * Checks, whether {@link #getNode()} has a value. + */ + boolean hasNode(); + + java.util.List getAnimals(); + + /** + * @see #getAnimals() + */ + test.nested.data.Holder setAnimals(java.util.List value); + + /** + * Adds a value to the {@link #getAnimals()} list. + */ + test.nested.data.Holder addAnimal(test.nested.data.Animal value); + + /** + * Removes a value from the {@link #getAnimals()} list. + */ + void removeAnimal(test.nested.data.Animal value); + + @Override + public test.nested.data.Holder registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Holder unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Holder readHolder(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Holder_Impl result = new test.nested.data.impl.Holder_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Holder readHolder(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Holder result = test.nested.data.impl.Holder_Impl.readHolder_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Holder} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Holder readHolder(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Holder_Impl.readHolder_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Level1.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Level1.java new file mode 100644 index 00000000..044936cf --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Level1.java @@ -0,0 +1,471 @@ +package test.nested.data; + +/** + * A hierarchy nested two levels deep. + */ +public interface Level1 extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Level2 extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Node extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.data.Level1.Level2.Node} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.data.Level1.Level2.Branch}. */ + BRANCH, + + /** Type literal for {@link test.nested.data.Level1.Level2.Root}. */ + ROOT, + + /** Type literal for {@link test.nested.data.Level1.Level2.Leaf}. */ + LEAF, + ; + + } + + /** Visitor interface for the {@link test.nested.data.Level1.Level2.Node} hierarchy.*/ + public interface Visitor extends test.nested.data.Level1.Level2.Composite.Visitor { + + /** Visit case for {@link test.nested.data.Level1.Level2.Leaf}.*/ + R visit(test.nested.data.Level1.Level2.Leaf self, A arg) throws E; + + } + + /** @see #getLabel() */ + String LABEL__PROP = "label"; + + /** Identifier for the property {@link #getLabel()} in binary format. */ + static final int LABEL__ID = 1; + + /** The type code of this instance. */ + TypeKind kind(); + + String getLabel(); + + /** + * @see #getLabel() + */ + test.nested.data.Level1.Level2.Node setLabel(String value); + + @Override + public test.nested.data.Level1.Level2.Node registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Level1.Level2.Node unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Node readNode(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.Level1.Level2.Node result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.data.Level1.Level2.Branch.BRANCH__TYPE: result = test.nested.data.Level1.Level2.Branch.readBranch(in); break; + case test.nested.data.Level1.Level2.Root.ROOT__TYPE: result = test.nested.data.Level1.Level2.Root.readRoot(in); break; + case test.nested.data.Level1.Level2.Leaf.LEAF__TYPE: result = test.nested.data.Level1.Level2.Leaf.readLeaf(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** The binary identifier for this concrete type in the polymorphic {@link test.nested.data.Level1.Level2.Node} hierarchy. */ + abstract int typeId(); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Node readNode(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.data.Level1.Level2.Node result; + switch (type) { + case test.nested.data.Level1.Level2.Branch.BRANCH__TYPE_ID: result = test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_Content(in); break; + case test.nested.data.Level1.Level2.Root.ROOT__TYPE_ID: result = test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_Content(in); break; + case test.nested.data.Level1.Level2.Leaf.LEAF__TYPE_ID: result = test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl.readLeaf_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Node} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Node readNode(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.readNode_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + /** + * Abstract intermediate. + */ + public interface Composite extends test.nested.data.Level1.Level2.Node { + + /** Visitor interface for the {@link test.nested.data.Level1.Level2.Composite} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.data.Level1.Level2.Branch}.*/ + R visit(test.nested.data.Level1.Level2.Branch self, A arg) throws E; + + /** Visit case for {@link test.nested.data.Level1.Level2.Root}.*/ + R visit(test.nested.data.Level1.Level2.Root self, A arg) throws E; + + } + + /** @see #getChildren() */ + String CHILDREN__PROP = "children"; + + /** Identifier for the property {@link #getChildren()} in binary format. */ + static final int CHILDREN__ID = 2; + + java.util.List getChildren(); + + /** + * @see #getChildren() + */ + test.nested.data.Level1.Level2.Composite setChildren(java.util.List value); + + /** + * Adds a value to the {@link #getChildren()} list. + */ + test.nested.data.Level1.Level2.Composite addChildren(test.nested.data.Level1.Level2.Node value); + + /** + * Removes a value from the {@link #getChildren()} list. + */ + void removeChildren(test.nested.data.Level1.Level2.Node value); + + @Override + test.nested.data.Level1.Level2.Composite setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Composite readComposite(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.Level1.Level2.Composite result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.data.Level1.Level2.Branch.BRANCH__TYPE: result = test.nested.data.Level1.Level2.Branch.readBranch(in); break; + case test.nested.data.Level1.Level2.Root.ROOT__TYPE: result = test.nested.data.Level1.Level2.Root.readRoot(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Composite readComposite(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.data.Level1.Level2.Composite result; + switch (type) { + case test.nested.data.Level1.Level2.Branch.BRANCH__TYPE_ID: result = test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_Content(in); break; + case test.nested.data.Level1.Level2.Root.ROOT__TYPE_ID: result = test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Composite} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Composite readComposite(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl.readComposite_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Leaf extends test.nested.data.Level1.Level2.Node { + + /** + * Creates a {@link test.nested.data.Level1.Level2.Leaf} instance. + */ + static test.nested.data.Level1.Level2.Leaf create() { + return new test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl(); + } + + /** Identifier for the {@link test.nested.data.Level1.Level2.Leaf} type in JSON format. */ + String LEAF__TYPE = "Leaf"; + + /** @see #getValue() */ + String VALUE__PROP = "value"; + + /** Identifier for the {@link test.nested.data.Level1.Level2.Leaf} type in binary format. */ + static final int LEAF__TYPE_ID = 3; + + /** Identifier for the property {@link #getValue()} in binary format. */ + static final int VALUE__ID = 2; + + int getValue(); + + /** + * @see #getValue() + */ + test.nested.data.Level1.Level2.Leaf setValue(int value); + + @Override + test.nested.data.Level1.Level2.Leaf setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Leaf readLeaf(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl result = new test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Leaf readLeaf(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Level1.Level2.Leaf result = test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl.readLeaf_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Leaf} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Leaf readLeaf(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl.readLeaf_XmlContent(in); + } + + } + public interface Branch extends test.nested.data.Level1.Level2.Composite { + + /** + * Creates a {@link test.nested.data.Level1.Level2.Branch} instance. + */ + static test.nested.data.Level1.Level2.Branch create() { + return new test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl(); + } + + /** Identifier for the {@link test.nested.data.Level1.Level2.Branch} type in JSON format. */ + String BRANCH__TYPE = "Branch"; + + /** @see #isExpanded() */ + String EXPANDED__PROP = "expanded"; + + /** Identifier for the {@link test.nested.data.Level1.Level2.Branch} type in binary format. */ + static final int BRANCH__TYPE_ID = 1; + + /** Identifier for the property {@link #isExpanded()} in binary format. */ + static final int EXPANDED__ID = 3; + + boolean isExpanded(); + + /** + * @see #isExpanded() + */ + test.nested.data.Level1.Level2.Branch setExpanded(boolean value); + + @Override + test.nested.data.Level1.Level2.Branch setChildren(java.util.List value); + + @Override + test.nested.data.Level1.Level2.Branch addChildren(test.nested.data.Level1.Level2.Node value); + + @Override + test.nested.data.Level1.Level2.Branch setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Branch readBranch(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl result = new test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Branch readBranch(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Level1.Level2.Branch result = test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Branch} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Branch readBranch(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_XmlContent(in); + } + + } + public interface Root extends test.nested.data.Level1.Level2.Composite { + + /** + * Creates a {@link test.nested.data.Level1.Level2.Root} instance. + */ + static test.nested.data.Level1.Level2.Root create() { + return new test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl(); + } + + /** Identifier for the {@link test.nested.data.Level1.Level2.Root} type in JSON format. */ + String ROOT__TYPE = "Root"; + + /** @see #getTitle() */ + String TITLE__PROP = "title"; + + /** Identifier for the {@link test.nested.data.Level1.Level2.Root} type in binary format. */ + static final int ROOT__TYPE_ID = 2; + + /** Identifier for the property {@link #getTitle()} in binary format. */ + static final int TITLE__ID = 3; + + String getTitle(); + + /** + * @see #getTitle() + */ + test.nested.data.Level1.Level2.Root setTitle(String value); + + @Override + test.nested.data.Level1.Level2.Root setChildren(java.util.List value); + + @Override + test.nested.data.Level1.Level2.Root addChildren(test.nested.data.Level1.Level2.Node value); + + @Override + test.nested.data.Level1.Level2.Root setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Root readRoot(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl result = new test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2.Root readRoot(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Level1.Level2.Root result = test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Root} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Root readRoot(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.data.Level1.Level2} instance. + */ + static test.nested.data.Level1.Level2 create() { + return new test.nested.data.impl.Level1_Impl.Level2_Impl(); + } + + /** Identifier for the {@link test.nested.data.Level1.Level2} type in JSON format. */ + String LEVEL_2__TYPE = "Level2"; + + @Override + public test.nested.data.Level1.Level2 registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Level1.Level2 unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2 readLevel2(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl result = new test.nested.data.impl.Level1_Impl.Level2_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1.Level2 readLevel2(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Level1.Level2 result = test.nested.data.impl.Level1_Impl.Level2_Impl.readLevel2_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Level2} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Level2 readLevel2(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.Level2_Impl.readLevel2_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.data.Level1} instance. + */ + static test.nested.data.Level1 create() { + return new test.nested.data.impl.Level1_Impl(); + } + + /** Identifier for the {@link test.nested.data.Level1} type in JSON format. */ + String LEVEL_1__TYPE = "Level1"; + + /** @see #getNode() */ + String NODE__PROP = "node"; + + /** @see #getNodes() */ + String NODES__PROP = "nodes"; + + /** Identifier for the property {@link #getNode()} in binary format. */ + static final int NODE__ID = 1; + + /** Identifier for the property {@link #getNodes()} in binary format. */ + static final int NODES__ID = 2; + + test.nested.data.Level1.Level2.Node getNode(); + + /** + * @see #getNode() + */ + test.nested.data.Level1 setNode(test.nested.data.Level1.Level2.Node value); + + /** + * Checks, whether {@link #getNode()} has a value. + */ + boolean hasNode(); + + java.util.List getNodes(); + + /** + * @see #getNodes() + */ + test.nested.data.Level1 setNodes(java.util.List value); + + /** + * Adds a value to the {@link #getNodes()} list. + */ + test.nested.data.Level1 addNodes(test.nested.data.Level1.Level2.Node value); + + /** + * Removes a value from the {@link #getNodes()} list. + */ + void removeNodes(test.nested.data.Level1.Level2.Node value); + + @Override + public test.nested.data.Level1 registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Level1 unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1 readLevel1(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl result = new test.nested.data.impl.Level1_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Level1 readLevel1(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Level1 result = test.nested.data.impl.Level1_Impl.readLevel1_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Level1} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Level1 readLevel1(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Level1_Impl.readLevel1_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Outer.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Outer.java new file mode 100644 index 00000000..488bc922 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Outer.java @@ -0,0 +1,357 @@ +package test.nested.data; + +/** + * Hierarchies with an abstract root declared inside other messages (issue #16). + */ +public interface Outer extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + /** + * Abstract root of a hierarchy nested in a top-level message. + */ + public interface Shape extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.data.Outer.Shape} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.data.Outer.Circle}. */ + CIRCLE, + + /** Type literal for {@link test.nested.data.Outer.Square}. */ + SQUARE, + + /** Type literal for {@link test.nested.data.Triangle}. */ + TRIANGLE, + ; + + } + + /** Visitor interface for the {@link test.nested.data.Outer.Shape} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.data.Outer.Circle}.*/ + R visit(test.nested.data.Outer.Circle self, A arg) throws E; + + /** Visit case for {@link test.nested.data.Outer.Square}.*/ + R visit(test.nested.data.Outer.Square self, A arg) throws E; + + /** Visit case for {@link test.nested.data.Triangle}.*/ + R visit(test.nested.data.Triangle self, A arg) throws E; + + } + + /** @see #getName() */ + String NAME__PROP = "name"; + + /** Identifier for the property {@link #getName()} in binary format. */ + static final int NAME__ID = 1; + + /** The type code of this instance. */ + TypeKind kind(); + + String getName(); + + /** + * @see #getName() + */ + test.nested.data.Outer.Shape setName(String value); + + @Override + public test.nested.data.Outer.Shape registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Outer.Shape unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Shape readShape(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.Outer.Shape result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.data.Outer.Circle.CIRCLE__TYPE: result = test.nested.data.Outer.Circle.readCircle(in); break; + case test.nested.data.Outer.Square.SQUARE__TYPE: result = test.nested.data.Outer.Square.readSquare(in); break; + case Triangle.TRIANGLE__TYPE: result = test.nested.data.Triangle.readTriangle(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** The binary identifier for this concrete type in the polymorphic {@link test.nested.data.Outer.Shape} hierarchy. */ + abstract int typeId(); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Shape readShape(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.data.Outer.Shape result; + switch (type) { + case test.nested.data.Outer.Circle.CIRCLE__TYPE_ID: result = test.nested.data.impl.Outer_Impl.Circle_Impl.readCircle_Content(in); break; + case test.nested.data.Outer.Square.SQUARE__TYPE_ID: result = test.nested.data.impl.Outer_Impl.Square_Impl.readSquare_Content(in); break; + case test.nested.data.Triangle.TRIANGLE__TYPE_ID: result = test.nested.data.impl.Triangle_Impl.readTriangle_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Shape} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shape readShape(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Circle extends test.nested.data.Outer.Shape { + + /** + * Creates a {@link test.nested.data.Outer.Circle} instance. + */ + static test.nested.data.Outer.Circle create() { + return new test.nested.data.impl.Outer_Impl.Circle_Impl(); + } + + /** Identifier for the {@link test.nested.data.Outer.Circle} type in JSON format. */ + String CIRCLE__TYPE = "Circle"; + + /** @see #getRadius() */ + String RADIUS__PROP = "radius"; + + /** Identifier for the {@link test.nested.data.Outer.Circle} type in binary format. */ + static final int CIRCLE__TYPE_ID = 1; + + /** Identifier for the property {@link #getRadius()} in binary format. */ + static final int RADIUS__ID = 2; + + int getRadius(); + + /** + * @see #getRadius() + */ + test.nested.data.Outer.Circle setRadius(int value); + + @Override + test.nested.data.Outer.Circle setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Circle readCircle(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Circle_Impl result = new test.nested.data.impl.Outer_Impl.Circle_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Circle readCircle(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Outer.Circle result = test.nested.data.impl.Outer_Impl.Circle_Impl.readCircle_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Circle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Circle readCircle(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Outer_Impl.Circle_Impl.readCircle_XmlContent(in); + } + + } + public interface Square extends test.nested.data.Outer.Shape { + + /** + * Creates a {@link test.nested.data.Outer.Square} instance. + */ + static test.nested.data.Outer.Square create() { + return new test.nested.data.impl.Outer_Impl.Square_Impl(); + } + + /** Identifier for the {@link test.nested.data.Outer.Square} type in JSON format. */ + String SQUARE__TYPE = "Square"; + + /** @see #getSide() */ + String SIDE__PROP = "side"; + + /** Identifier for the {@link test.nested.data.Outer.Square} type in binary format. */ + static final int SQUARE__TYPE_ID = 2; + + /** Identifier for the property {@link #getSide()} in binary format. */ + static final int SIDE__ID = 2; + + int getSide(); + + /** + * @see #getSide() + */ + test.nested.data.Outer.Square setSide(int value); + + @Override + test.nested.data.Outer.Square setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Square readSquare(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Square_Impl result = new test.nested.data.impl.Outer_Impl.Square_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Square readSquare(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Outer.Square result = test.nested.data.impl.Outer_Impl.Square_Impl.readSquare_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Square} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Square readSquare(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Outer_Impl.Square_Impl.readSquare_XmlContent(in); + } + + } + /** + * A sibling message holding values of the nested abstract type. + */ + public interface Drawing extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.nested.data.Outer.Drawing} instance. + */ + static test.nested.data.Outer.Drawing create() { + return new test.nested.data.impl.Outer_Impl.Drawing_Impl(); + } + + /** Identifier for the {@link test.nested.data.Outer.Drawing} type in JSON format. */ + String DRAWING__TYPE = "Drawing"; + + /** @see #getMain() */ + String MAIN__PROP = "main"; + + /** @see #getShapes() */ + String SHAPES__PROP = "shapes"; + + /** Identifier for the property {@link #getMain()} in binary format. */ + static final int MAIN__ID = 1; + + /** Identifier for the property {@link #getShapes()} in binary format. */ + static final int SHAPES__ID = 2; + + test.nested.data.Outer.Shape getMain(); + + /** + * @see #getMain() + */ + test.nested.data.Outer.Drawing setMain(test.nested.data.Outer.Shape value); + + /** + * Checks, whether {@link #getMain()} has a value. + */ + boolean hasMain(); + + java.util.List getShapes(); + + /** + * @see #getShapes() + */ + test.nested.data.Outer.Drawing setShapes(java.util.List value); + + /** + * Adds a value to the {@link #getShapes()} list. + */ + test.nested.data.Outer.Drawing addShape(test.nested.data.Outer.Shape value); + + /** + * Removes a value from the {@link #getShapes()} list. + */ + void removeShape(test.nested.data.Outer.Shape value); + + @Override + public test.nested.data.Outer.Drawing registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Outer.Drawing unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Drawing readDrawing(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Drawing_Impl result = new test.nested.data.impl.Outer_Impl.Drawing_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer.Drawing readDrawing(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Outer.Drawing result = test.nested.data.impl.Outer_Impl.Drawing_Impl.readDrawing_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Drawing} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Drawing readDrawing(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Outer_Impl.Drawing_Impl.readDrawing_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.data.Outer} instance. + */ + static test.nested.data.Outer create() { + return new test.nested.data.impl.Outer_Impl(); + } + + /** Identifier for the {@link test.nested.data.Outer} type in JSON format. */ + String OUTER__TYPE = "Outer"; + + /** @see #getShape() */ + String SHAPE__PROP = "shape"; + + /** Identifier for the property {@link #getShape()} in binary format. */ + static final int SHAPE__ID = 1; + + /** + * A field of the nested abstract type in the outer message itself. + */ + test.nested.data.Outer.Shape getShape(); + + /** + * @see #getShape() + */ + test.nested.data.Outer setShape(test.nested.data.Outer.Shape value); + + /** + * Checks, whether {@link #getShape()} has a value. + */ + boolean hasShape(); + + @Override + public test.nested.data.Outer registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Outer unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer readOuter(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl result = new test.nested.data.impl.Outer_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Outer readOuter(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Outer result = test.nested.data.impl.Outer_Impl.readOuter_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Outer} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Outer readOuter(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Outer_Impl.readOuter_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Triangle.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Triangle.java new file mode 100644 index 00000000..31b6e109 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Triangle.java @@ -0,0 +1,71 @@ +package test.nested.data; + +/** + * A top-level message extending a nested abstract message. + */ +public interface Triangle extends test.nested.data.Outer.Shape { + + /** + * Creates a {@link test.nested.data.Triangle} instance. + */ + static test.nested.data.Triangle create() { + return new test.nested.data.impl.Triangle_Impl(); + } + + /** Identifier for the {@link test.nested.data.Triangle} type in JSON format. */ + String TRIANGLE__TYPE = "Triangle"; + + /** @see #getBase() */ + String BASE__PROP = "base"; + + /** @see #getHeight() */ + String HEIGHT__PROP = "height"; + + /** Identifier for the {@link test.nested.data.Triangle} type in binary format. */ + static final int TRIANGLE__TYPE_ID = 3; + + /** Identifier for the property {@link #getBase()} in binary format. */ + static final int BASE__ID = 2; + + /** Identifier for the property {@link #getHeight()} in binary format. */ + static final int HEIGHT__ID = 3; + + int getBase(); + + /** + * @see #getBase() + */ + test.nested.data.Triangle setBase(int value); + + int getHeight(); + + /** + * @see #getHeight() + */ + test.nested.data.Triangle setHeight(int value); + + @Override + test.nested.data.Triangle setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Triangle readTriangle(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Triangle_Impl result = new test.nested.data.impl.Triangle_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Triangle readTriangle(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Triangle result = test.nested.data.impl.Triangle_Impl.readTriangle_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Triangle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Triangle readTriangle(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Triangle_Impl.readTriangle_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Zoo.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Zoo.java new file mode 100644 index 00000000..14e5f003 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/Zoo.java @@ -0,0 +1,254 @@ +package test.nested.data; + +/** + * A container for sub-messages extending a top-level abstract message. + */ +public interface Zoo extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Cat extends test.nested.data.Animal { + + /** + * Creates a {@link test.nested.data.Zoo.Cat} instance. + */ + static test.nested.data.Zoo.Cat create() { + return new test.nested.data.impl.Zoo_Impl.Cat_Impl(); + } + + /** Identifier for the {@link test.nested.data.Zoo.Cat} type in JSON format. */ + String CAT__TYPE = "Cat"; + + /** @see #isIndoor() */ + String INDOOR__PROP = "indoor"; + + /** Identifier for the {@link test.nested.data.Zoo.Cat} type in binary format. */ + static final int CAT__TYPE_ID = 1; + + /** Identifier for the property {@link #isIndoor()} in binary format. */ + static final int INDOOR__ID = 2; + + boolean isIndoor(); + + /** + * @see #isIndoor() + */ + test.nested.data.Zoo.Cat setIndoor(boolean value); + + @Override + test.nested.data.Zoo.Cat setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Cat readCat(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl.Cat_Impl result = new test.nested.data.impl.Zoo_Impl.Cat_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Cat readCat(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Zoo.Cat result = test.nested.data.impl.Zoo_Impl.Cat_Impl.readCat_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Cat} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Cat readCat(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Zoo_Impl.Cat_Impl.readCat_XmlContent(in); + } + + } + /** + * A nested abstract intermediate below a top-level root. + */ + public interface Bird extends test.nested.data.Animal { + + /** Visitor interface for the {@link test.nested.data.Zoo.Bird} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.data.Zoo.Parrot}.*/ + R visit(test.nested.data.Zoo.Parrot self, A arg) throws E; + + } + + /** @see #getWingspan() */ + String WINGSPAN__PROP = "wingspan"; + + /** Identifier for the property {@link #getWingspan()} in binary format. */ + static final int WINGSPAN__ID = 2; + + double getWingspan(); + + /** + * @see #getWingspan() + */ + test.nested.data.Zoo.Bird setWingspan(double value); + + @Override + test.nested.data.Zoo.Bird setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Bird readBird(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.Zoo.Bird result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.data.Zoo.Parrot.PARROT__TYPE: result = test.nested.data.Zoo.Parrot.readParrot(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Bird readBird(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.data.Zoo.Bird result; + switch (type) { + case test.nested.data.Zoo.Parrot.PARROT__TYPE_ID: result = test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Bird} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Bird readBird(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Zoo_Impl.Bird_Impl.readBird_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Parrot extends test.nested.data.Zoo.Bird { + + /** + * Creates a {@link test.nested.data.Zoo.Parrot} instance. + */ + static test.nested.data.Zoo.Parrot create() { + return new test.nested.data.impl.Zoo_Impl.Parrot_Impl(); + } + + /** Identifier for the {@link test.nested.data.Zoo.Parrot} type in JSON format. */ + String PARROT__TYPE = "Parrot"; + + /** @see #getWords() */ + String WORDS__PROP = "words"; + + /** Identifier for the {@link test.nested.data.Zoo.Parrot} type in binary format. */ + static final int PARROT__TYPE_ID = 2; + + /** Identifier for the property {@link #getWords()} in binary format. */ + static final int WORDS__ID = 3; + + java.util.List getWords(); + + /** + * @see #getWords() + */ + test.nested.data.Zoo.Parrot setWords(java.util.List value); + + /** + * Adds a value to the {@link #getWords()} list. + */ + test.nested.data.Zoo.Parrot addWord(String value); + + /** + * Removes a value from the {@link #getWords()} list. + */ + void removeWord(String value); + + @Override + test.nested.data.Zoo.Parrot setWingspan(double value); + + @Override + test.nested.data.Zoo.Parrot setName(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Parrot readParrot(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl.Parrot_Impl result = new test.nested.data.impl.Zoo_Impl.Parrot_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo.Parrot readParrot(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Zoo.Parrot result = test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Parrot} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Parrot readParrot(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.data.Zoo} instance. + */ + static test.nested.data.Zoo create() { + return new test.nested.data.impl.Zoo_Impl(); + } + + /** Identifier for the {@link test.nested.data.Zoo} type in JSON format. */ + String ZOO__TYPE = "Zoo"; + + /** @see #getAnimals() */ + String ANIMALS__PROP = "animals"; + + /** Identifier for the property {@link #getAnimals()} in binary format. */ + static final int ANIMALS__ID = 1; + + java.util.List getAnimals(); + + /** + * @see #getAnimals() + */ + test.nested.data.Zoo setAnimals(java.util.List value); + + /** + * Adds a value to the {@link #getAnimals()} list. + */ + test.nested.data.Zoo addAnimal(test.nested.data.Animal value); + + /** + * Removes a value from the {@link #getAnimals()} list. + */ + void removeAnimal(test.nested.data.Animal value); + + @Override + public test.nested.data.Zoo registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.data.Zoo unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo readZoo(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl result = new test.nested.data.impl.Zoo_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.data.Zoo readZoo(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.data.Zoo result = test.nested.data.impl.Zoo_Impl.readZoo_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Zoo} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Zoo readZoo(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.data.impl.Zoo_Impl.readZoo_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Animal_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Animal_Impl.java new file mode 100644 index 00000000..a3b6ecbd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Animal_Impl.java @@ -0,0 +1,253 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Animal}. + */ +public abstract class Animal_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Animal { + + private String _name = ""; + + /** + * Creates a {@link Animal_Impl} instance. + */ + public Animal_Impl() { + super(); + } + + @Override + public final String getName() { + return _name; + } + + @Override + public test.nested.data.Animal setName(String value) { + internalSetName(value); + return this; + } + + /** Internal setter for {@link #getName()} without chain call utility. */ + protected final void internalSetName(String value) { + _listener.beforeSet(this, NAME__PROP, value); + _name = value; + _listener.afterChanged(this, NAME__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Animal registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Animal unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NAME__PROP: return getName(); + default: return test.nested.data.Animal.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NAME__PROP: internalSetName((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NAME__PROP); + out.value(getName()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + out.name(0); + out.value(typeId()); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(NAME__ID); + out.value(getName()); + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case NAME__ID: setName(in.nextString()); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Animal} type. */ + public static final String ANIMAL__XML_ELEMENT = "animal"; + + /** XML attribute or element name of a {@link #getName} property. */ + private static final String NAME__XML_ATTR = "name"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NAME__XML_ATTR, getName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.data.Animal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Animal_Impl readAnimal_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.data.impl.Zoo_Impl.Cat_Impl.CAT__XML_ELEMENT: { + return test.nested.data.impl.Zoo_Impl.Cat_Impl.readCat_XmlContent(in); + } + + case test.nested.data.impl.Zoo_Impl.Parrot_Impl.PARROT__XML_ELEMENT: { + return test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NAME__XML_ATTR: { + setName(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NAME__XML_ATTR: { + setName(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Holder_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Holder_Impl.java new file mode 100644 index 00000000..c179c4a4 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Holder_Impl.java @@ -0,0 +1,538 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Holder}. + */ +public class Holder_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Holder { + + private test.nested.data.Outer.Shape _shape = null; + + private final java.util.List _shapes = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Outer.Shape element) { + _listener.beforeAdd(Holder_Impl.this, SHAPES__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Outer.Shape element) { + _listener.afterRemove(Holder_Impl.this, SHAPES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Holder_Impl.this, SHAPES__PROP); + } + }; + + private test.nested.data.Level1.Level2.Node _node = null; + + private final java.util.List _animals = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Animal element) { + _listener.beforeAdd(Holder_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Animal element) { + _listener.afterRemove(Holder_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Holder_Impl.this, ANIMALS__PROP); + } + }; + + /** + * Creates a {@link Holder_Impl} instance. + * + * @see test.nested.data.Holder#create() + */ + public Holder_Impl() { + super(); + } + + @Override + public final test.nested.data.Outer.Shape getShape() { + return _shape; + } + + @Override + public test.nested.data.Holder setShape(test.nested.data.Outer.Shape value) { + internalSetShape(value); + return this; + } + + /** Internal setter for {@link #getShape()} without chain call utility. */ + protected final void internalSetShape(test.nested.data.Outer.Shape value) { + _listener.beforeSet(this, SHAPE__PROP, value); + _shape = value; + _listener.afterChanged(this, SHAPE__PROP); + } + + @Override + public final boolean hasShape() { + return _shape != null; + } + + @Override + public final java.util.List getShapes() { + return _shapes; + } + + @Override + public test.nested.data.Holder setShapes(java.util.List value) { + internalSetShapes(value); + return this; + } + + /** Internal setter for {@link #getShapes()} without chain call utility. */ + protected final void internalSetShapes(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'shapes' cannot be null."); + _shapes.clear(); + _shapes.addAll(value); + } + + @Override + public test.nested.data.Holder addShapes(test.nested.data.Outer.Shape value) { + internalAddShapes(value); + return this; + } + + /** Implementation of {@link #addShapes(test.nested.data.Outer.Shape)} without chain call utility. */ + protected final void internalAddShapes(test.nested.data.Outer.Shape value) { + _shapes.add(value); + } + + @Override + public final void removeShapes(test.nested.data.Outer.Shape value) { + _shapes.remove(value); + } + + @Override + public final test.nested.data.Level1.Level2.Node getNode() { + return _node; + } + + @Override + public test.nested.data.Holder setNode(test.nested.data.Level1.Level2.Node value) { + internalSetNode(value); + return this; + } + + /** Internal setter for {@link #getNode()} without chain call utility. */ + protected final void internalSetNode(test.nested.data.Level1.Level2.Node value) { + _listener.beforeSet(this, NODE__PROP, value); + _node = value; + _listener.afterChanged(this, NODE__PROP); + } + + @Override + public final boolean hasNode() { + return _node != null; + } + + @Override + public final java.util.List getAnimals() { + return _animals; + } + + @Override + public test.nested.data.Holder setAnimals(java.util.List value) { + internalSetAnimals(value); + return this; + } + + /** Internal setter for {@link #getAnimals()} without chain call utility. */ + protected final void internalSetAnimals(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'animals' cannot be null."); + _animals.clear(); + _animals.addAll(value); + } + + @Override + public test.nested.data.Holder addAnimal(test.nested.data.Animal value) { + internalAddAnimal(value); + return this; + } + + /** Implementation of {@link #addAnimal(test.nested.data.Animal)} without chain call utility. */ + protected final void internalAddAnimal(test.nested.data.Animal value) { + _animals.add(value); + } + + @Override + public final void removeAnimal(test.nested.data.Animal value) { + _animals.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Holder registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Holder unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return HOLDER__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SHAPE__PROP, + SHAPES__PROP, + NODE__PROP, + ANIMALS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SHAPE__PROP: return getShape(); + case SHAPES__PROP: return getShapes(); + case NODE__PROP: return getNode(); + case ANIMALS__PROP: return getAnimals(); + default: return test.nested.data.Holder.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SHAPE__PROP: internalSetShape((test.nested.data.Outer.Shape) value); break; + case SHAPES__PROP: internalSetShapes(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Outer.Shape.class, value)); break; + case NODE__PROP: internalSetNode((test.nested.data.Level1.Level2.Node) value); break; + case ANIMALS__PROP: internalSetAnimals(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Animal.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasShape()) { + out.name(SHAPE__PROP); + getShape().writeTo(out); + } + out.name(SHAPES__PROP); + out.beginArray(); + for (test.nested.data.Outer.Shape x : getShapes()) { + x.writeTo(out); + } + out.endArray(); + if (hasNode()) { + out.name(NODE__PROP); + getNode().writeTo(out); + } + out.name(ANIMALS__PROP); + out.beginArray(); + for (test.nested.data.Animal x : getAnimals()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SHAPE__PROP: setShape(test.nested.data.Outer.Shape.readShape(in)); break; + case SHAPES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Outer.Shape.readShape(in)); + } + in.endArray(); + setShapes(newValue); + } + break; + case NODE__PROP: setNode(test.nested.data.Level1.Level2.Node.readNode(in)); break; + case ANIMALS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Animal.readAnimal(in)); + } + in.endArray(); + setAnimals(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasShape()) { + out.name(SHAPE__ID); + getShape().writeTo(out); + } + out.name(SHAPES__ID); + { + java.util.List values = getShapes(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Outer.Shape x : values) { + x.writeTo(out); + } + out.endArray(); + } + if (hasNode()) { + out.name(NODE__ID); + getNode().writeTo(out); + } + out.name(ANIMALS__ID); + { + java.util.List values = getAnimals(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Animal x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Holder} from a polymorphic composition. */ + public static test.nested.data.Holder readHolder_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Holder_Impl result = new Holder_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case SHAPE__ID: setShape(test.nested.data.Outer.Shape.readShape(in)); break; + case SHAPES__ID: { + in.beginArray(); + while (in.hasNext()) { + addShapes(test.nested.data.Outer.Shape.readShape(in)); + } + in.endArray(); + } + break; + case NODE__ID: setNode(test.nested.data.Level1.Level2.Node.readNode(in)); break; + case ANIMALS__ID: { + in.beginArray(); + while (in.hasNext()) { + addAnimal(test.nested.data.Animal.readAnimal(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Holder} type. */ + public static final String HOLDER__XML_ELEMENT = "holder"; + + /** XML attribute or element name of a {@link #getShape} property. */ + private static final String SHAPE__XML_ATTR = "shape"; + + /** XML attribute or element name of a {@link #getShapes} property. */ + private static final String SHAPES__XML_ATTR = "shapes"; + + /** XML attribute or element name of a {@link #getNode} property. */ + private static final String NODE__XML_ATTR = "node"; + + /** XML attribute or element name of a {@link #getAnimals} property. */ + private static final String ANIMALS__XML_ATTR = "animals"; + + @Override + public String getXmlTagName() { + return HOLDER__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasShape()) { + out.writeStartElement(SHAPE__XML_ATTR); + getShape().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(SHAPES__XML_ATTR); + for (test.nested.data.Outer.Shape element : getShapes()) { + element.writeTo(out); + } + out.writeEndElement(); + if (hasNode()) { + out.writeStartElement(NODE__XML_ATTR); + getNode().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(ANIMALS__XML_ATTR); + for (test.nested.data.Animal element : getAnimals()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.data.Holder} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Holder_Impl readHolder_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Holder_Impl result = new Holder_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SHAPE__XML_ATTR: { + in.nextTag(); + setShape(test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case SHAPES__XML_ATTR: { + internalReadShapesListXml(in); + break; + } + case NODE__XML_ATTR: { + in.nextTag(); + setNode(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.readNode_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case ANIMALS__XML_ATTR: { + internalReadAnimalsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadShapesListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addShapes(test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in)); + } + } + + private void internalReadAnimalsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addAnimal(test.nested.data.impl.Animal_Impl.readAnimal_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Level1_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Level1_Impl.java new file mode 100644 index 00000000..3601cdd2 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Level1_Impl.java @@ -0,0 +1,1682 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Level1}. + */ +public class Level1_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Level1 { + /** + * Implementation of {@link test.nested.data.Level1.Level2}. + */ + public static class Level2_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Level1.Level2 { + /** + * Implementation of {@link test.nested.data.Level1.Level2.Node}. + */ + public static abstract class Node_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Level1.Level2.Node { + + private String _label = ""; + + /** + * Creates a {@link Node_Impl} instance. + */ + public Node_Impl() { + super(); + } + + @Override + public final String getLabel() { + return _label; + } + + @Override + public test.nested.data.Level1.Level2.Node setLabel(String value) { + internalSetLabel(value); + return this; + } + + /** Internal setter for {@link #getLabel()} without chain call utility. */ + protected final void internalSetLabel(String value) { + _listener.beforeSet(this, LABEL__PROP, value); + _label = value; + _listener.afterChanged(this, LABEL__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Level1.Level2.Node registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Level1.Level2.Node unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + LABEL__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case LABEL__PROP: return getLabel(); + default: return test.nested.data.Level1.Level2.Node.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case LABEL__PROP: internalSetLabel((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(LABEL__PROP); + out.value(getLabel()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case LABEL__PROP: setLabel(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + out.name(0); + out.value(typeId()); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(LABEL__ID); + out.value(getLabel()); + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case LABEL__ID: setLabel(in.nextString()); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2.Node} type. */ + public static final String NODE__XML_ELEMENT = "node"; + + /** XML attribute or element name of a {@link #getLabel} property. */ + private static final String LABEL__XML_ATTR = "label"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(LABEL__XML_ATTR, getLabel()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.data.Level1.Level2.Node} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Node_Impl readNode_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.BRANCH__XML_ELEMENT: { + return test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_XmlContent(in); + } + + case test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.ROOT__XML_ELEMENT: { + return test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_XmlContent(in); + } + + case test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl.LEAF__XML_ELEMENT: { + return test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl.readLeaf_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case LABEL__XML_ATTR: { + setLabel(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case LABEL__XML_ATTR: { + setLabel(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + /** + * Implementation of {@link test.nested.data.Level1.Level2.Composite}. + */ + public static abstract class Composite_Impl extends test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl implements test.nested.data.Level1.Level2.Composite { + + private final java.util.List _children = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Level1.Level2.Node element) { + _listener.beforeAdd(Composite_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Level1.Level2.Node element) { + _listener.afterRemove(Composite_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Composite_Impl.this, CHILDREN__PROP); + } + }; + + /** + * Creates a {@link Composite_Impl} instance. + */ + public Composite_Impl() { + super(); + } + + @Override + public final java.util.List getChildren() { + return _children; + } + + @Override + public test.nested.data.Level1.Level2.Composite setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + /** Internal setter for {@link #getChildren()} without chain call utility. */ + protected final void internalSetChildren(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'children' cannot be null."); + _children.clear(); + _children.addAll(value); + } + + @Override + public test.nested.data.Level1.Level2.Composite addChildren(test.nested.data.Level1.Level2.Node value) { + internalAddChildren(value); + return this; + } + + /** Implementation of {@link #addChildren(test.nested.data.Level1.Level2.Node)} without chain call utility. */ + protected final void internalAddChildren(test.nested.data.Level1.Level2.Node value) { + _children.add(value); + } + + @Override + public final void removeChildren(test.nested.data.Level1.Level2.Node value) { + _children.remove(value); + } + + @Override + public test.nested.data.Level1.Level2.Composite setLabel(String value) { + internalSetLabel(value); + return this; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + CHILDREN__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case CHILDREN__PROP: return getChildren(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case CHILDREN__PROP: internalSetChildren(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Level1.Level2.Node.class, value)); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(CHILDREN__PROP); + out.beginArray(); + for (test.nested.data.Level1.Level2.Node x : getChildren()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case CHILDREN__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Level1.Level2.Node.readNode(in)); + } + in.endArray(); + setChildren(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(CHILDREN__ID); + { + java.util.List values = getChildren(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Level1.Level2.Node x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case CHILDREN__ID: { + in.beginArray(); + while (in.hasNext()) { + addChildren(test.nested.data.Level1.Level2.Node.readNode(in)); + } + in.endArray(); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2.Composite} type. */ + public static final String COMPOSITE__XML_ELEMENT = "composite"; + + /** XML attribute or element name of a {@link #getChildren} property. */ + private static final String CHILDREN__XML_ATTR = "children"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + out.writeStartElement(CHILDREN__XML_ATTR); + for (test.nested.data.Level1.Level2.Node element : getChildren()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.data.Level1.Level2.Composite} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Composite_Impl readComposite_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.BRANCH__XML_ELEMENT: { + return test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl.readBranch_XmlContent(in); + } + + case test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.ROOT__XML_ELEMENT: { + return test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl.readRoot_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case CHILDREN__XML_ATTR: { + internalReadChildrenListXml(in); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + private void internalReadChildrenListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addChildren(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.readNode_XmlContent(in)); + } + } + + @Override + public final R visit(test.nested.data.Level1.Level2.Node.Visitor v, A arg) throws E { + return visit((test.nested.data.Level1.Level2.Composite.Visitor) v, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Level1.Level2.Leaf}. + */ + public static class Leaf_Impl extends test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl implements test.nested.data.Level1.Level2.Leaf { + + private int _value = 0; + + /** + * Creates a {@link Leaf_Impl} instance. + * + * @see test.nested.data.Level1.Level2.Leaf#create() + */ + public Leaf_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.LEAF; + } + + @Override + public final int getValue() { + return _value; + } + + @Override + public test.nested.data.Level1.Level2.Leaf setValue(int value) { + internalSetValue(value); + return this; + } + + /** Internal setter for {@link #getValue()} without chain call utility. */ + protected final void internalSetValue(int value) { + _listener.beforeSet(this, VALUE__PROP, value); + _value = value; + _listener.afterChanged(this, VALUE__PROP); + } + + @Override + public test.nested.data.Level1.Level2.Leaf setLabel(String value) { + internalSetLabel(value); + return this; + } + + @Override + public String jsonType() { + return LEAF__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + VALUE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case VALUE__PROP: return getValue(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case VALUE__PROP: internalSetValue((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(VALUE__PROP); + out.value(getValue()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case VALUE__PROP: setValue(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return LEAF__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(VALUE__ID); + out.value(getValue()); + } + + /** Helper for creating an object of type {@link test.nested.data.Level1.Level2.Leaf} from a polymorphic composition. */ + public static test.nested.data.Level1.Level2.Leaf readLeaf_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Leaf_Impl result = new Leaf_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case VALUE__ID: setValue(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2.Leaf} type. */ + public static final String LEAF__XML_ELEMENT = "leaf"; + + /** XML attribute or element name of a {@link #getValue} property. */ + private static final String VALUE__XML_ATTR = "value"; + + @Override + public String getXmlTagName() { + return LEAF__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(VALUE__XML_ATTR, Integer.toString(getValue())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Level1.Level2.Leaf} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Leaf_Impl readLeaf_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Leaf_Impl result = new Leaf_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case VALUE__XML_ATTR: { + setValue(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case VALUE__XML_ATTR: { + setValue(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Level1.Level2.Node.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Level1.Level2.Branch}. + */ + public static class Branch_Impl extends test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl implements test.nested.data.Level1.Level2.Branch { + + private boolean _expanded = false; + + /** + * Creates a {@link Branch_Impl} instance. + * + * @see test.nested.data.Level1.Level2.Branch#create() + */ + public Branch_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.BRANCH; + } + + @Override + public final boolean isExpanded() { + return _expanded; + } + + @Override + public test.nested.data.Level1.Level2.Branch setExpanded(boolean value) { + internalSetExpanded(value); + return this; + } + + /** Internal setter for {@link #isExpanded()} without chain call utility. */ + protected final void internalSetExpanded(boolean value) { + _listener.beforeSet(this, EXPANDED__PROP, value); + _expanded = value; + _listener.afterChanged(this, EXPANDED__PROP); + } + + @Override + public test.nested.data.Level1.Level2.Branch setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + @Override + public test.nested.data.Level1.Level2.Branch addChildren(test.nested.data.Level1.Level2.Node value) { + internalAddChildren(value); + return this; + } + + @Override + public test.nested.data.Level1.Level2.Branch setLabel(String value) { + internalSetLabel(value); + return this; + } + + @Override + public String jsonType() { + return BRANCH__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + EXPANDED__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case EXPANDED__PROP: return isExpanded(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case EXPANDED__PROP: internalSetExpanded((boolean) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(EXPANDED__PROP); + out.value(isExpanded()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case EXPANDED__PROP: setExpanded(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return BRANCH__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(EXPANDED__ID); + out.value(isExpanded()); + } + + /** Helper for creating an object of type {@link test.nested.data.Level1.Level2.Branch} from a polymorphic composition. */ + public static test.nested.data.Level1.Level2.Branch readBranch_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Branch_Impl result = new Branch_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case EXPANDED__ID: setExpanded(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2.Branch} type. */ + public static final String BRANCH__XML_ELEMENT = "branch"; + + /** XML attribute or element name of a {@link #isExpanded} property. */ + private static final String EXPANDED__XML_ATTR = "expanded"; + + @Override + public String getXmlTagName() { + return BRANCH__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(EXPANDED__XML_ATTR, Boolean.toString(isExpanded())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Level1.Level2.Branch} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Branch_Impl readBranch_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Branch_Impl result = new Branch_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case EXPANDED__XML_ATTR: { + setExpanded(Boolean.parseBoolean(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case EXPANDED__XML_ATTR: { + setExpanded(Boolean.parseBoolean(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Level1.Level2.Composite.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Level1.Level2.Root}. + */ + public static class Root_Impl extends test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl implements test.nested.data.Level1.Level2.Root { + + private String _title = ""; + + /** + * Creates a {@link Root_Impl} instance. + * + * @see test.nested.data.Level1.Level2.Root#create() + */ + public Root_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.ROOT; + } + + @Override + public final String getTitle() { + return _title; + } + + @Override + public test.nested.data.Level1.Level2.Root setTitle(String value) { + internalSetTitle(value); + return this; + } + + /** Internal setter for {@link #getTitle()} without chain call utility. */ + protected final void internalSetTitle(String value) { + _listener.beforeSet(this, TITLE__PROP, value); + _title = value; + _listener.afterChanged(this, TITLE__PROP); + } + + @Override + public test.nested.data.Level1.Level2.Root setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + @Override + public test.nested.data.Level1.Level2.Root addChildren(test.nested.data.Level1.Level2.Node value) { + internalAddChildren(value); + return this; + } + + @Override + public test.nested.data.Level1.Level2.Root setLabel(String value) { + internalSetLabel(value); + return this; + } + + @Override + public String jsonType() { + return ROOT__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TITLE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Level1_Impl.Level2_Impl.Composite_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TITLE__PROP: return getTitle(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TITLE__PROP: internalSetTitle((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TITLE__PROP); + out.value(getTitle()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TITLE__PROP: setTitle(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return ROOT__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TITLE__ID); + out.value(getTitle()); + } + + /** Helper for creating an object of type {@link test.nested.data.Level1.Level2.Root} from a polymorphic composition. */ + public static test.nested.data.Level1.Level2.Root readRoot_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl.Root_Impl result = new Root_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case TITLE__ID: setTitle(in.nextString()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2.Root} type. */ + public static final String ROOT__XML_ELEMENT = "root"; + + /** XML attribute or element name of a {@link #getTitle} property. */ + private static final String TITLE__XML_ATTR = "title"; + + @Override + public String getXmlTagName() { + return ROOT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(TITLE__XML_ATTR, getTitle()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Level1.Level2.Root} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Root_Impl readRoot_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Root_Impl result = new Root_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case TITLE__XML_ATTR: { + setTitle(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TITLE__XML_ATTR: { + setTitle(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Level1.Level2.Composite.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + /** + * Creates a {@link Level2_Impl} instance. + * + * @see test.nested.data.Level1.Level2#create() + */ + public Level2_Impl() { + super(); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Level1.Level2 registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Level1.Level2 unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return LEVEL_2__TYPE; + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + // No fields to write, hook for subclasses. + } + + /** Helper for creating an object of type {@link test.nested.data.Level1.Level2} from a polymorphic composition. */ + public static test.nested.data.Level1.Level2 readLevel2_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl.Level2_Impl result = new Level2_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Level1.Level2} type. */ + public static final String LEVEL_2__XML_ELEMENT = "level-2"; + + @Override + public String getXmlTagName() { + return LEVEL_2__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.data.Level1.Level2} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Level2_Impl readLevel2_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Level2_Impl result = new Level2_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + + private test.nested.data.Level1.Level2.Node _node = null; + + private final java.util.List _nodes = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Level1.Level2.Node element) { + _listener.beforeAdd(Level1_Impl.this, NODES__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Level1.Level2.Node element) { + _listener.afterRemove(Level1_Impl.this, NODES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Level1_Impl.this, NODES__PROP); + } + }; + + /** + * Creates a {@link Level1_Impl} instance. + * + * @see test.nested.data.Level1#create() + */ + public Level1_Impl() { + super(); + } + + @Override + public final test.nested.data.Level1.Level2.Node getNode() { + return _node; + } + + @Override + public test.nested.data.Level1 setNode(test.nested.data.Level1.Level2.Node value) { + internalSetNode(value); + return this; + } + + /** Internal setter for {@link #getNode()} without chain call utility. */ + protected final void internalSetNode(test.nested.data.Level1.Level2.Node value) { + _listener.beforeSet(this, NODE__PROP, value); + _node = value; + _listener.afterChanged(this, NODE__PROP); + } + + @Override + public final boolean hasNode() { + return _node != null; + } + + @Override + public final java.util.List getNodes() { + return _nodes; + } + + @Override + public test.nested.data.Level1 setNodes(java.util.List value) { + internalSetNodes(value); + return this; + } + + /** Internal setter for {@link #getNodes()} without chain call utility. */ + protected final void internalSetNodes(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'nodes' cannot be null."); + _nodes.clear(); + _nodes.addAll(value); + } + + @Override + public test.nested.data.Level1 addNodes(test.nested.data.Level1.Level2.Node value) { + internalAddNodes(value); + return this; + } + + /** Implementation of {@link #addNodes(test.nested.data.Level1.Level2.Node)} without chain call utility. */ + protected final void internalAddNodes(test.nested.data.Level1.Level2.Node value) { + _nodes.add(value); + } + + @Override + public final void removeNodes(test.nested.data.Level1.Level2.Node value) { + _nodes.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Level1 registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Level1 unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return LEVEL_1__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NODE__PROP, + NODES__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NODE__PROP: return getNode(); + case NODES__PROP: return getNodes(); + default: return test.nested.data.Level1.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NODE__PROP: internalSetNode((test.nested.data.Level1.Level2.Node) value); break; + case NODES__PROP: internalSetNodes(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Level1.Level2.Node.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasNode()) { + out.name(NODE__PROP); + getNode().writeTo(out); + } + out.name(NODES__PROP); + out.beginArray(); + for (test.nested.data.Level1.Level2.Node x : getNodes()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NODE__PROP: setNode(test.nested.data.Level1.Level2.Node.readNode(in)); break; + case NODES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Level1.Level2.Node.readNode(in)); + } + in.endArray(); + setNodes(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasNode()) { + out.name(NODE__ID); + getNode().writeTo(out); + } + out.name(NODES__ID); + { + java.util.List values = getNodes(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Level1.Level2.Node x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Level1} from a polymorphic composition. */ + public static test.nested.data.Level1 readLevel1_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Level1_Impl result = new Level1_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case NODE__ID: setNode(test.nested.data.Level1.Level2.Node.readNode(in)); break; + case NODES__ID: { + in.beginArray(); + while (in.hasNext()) { + addNodes(test.nested.data.Level1.Level2.Node.readNode(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Level1} type. */ + public static final String LEVEL_1__XML_ELEMENT = "level-1"; + + /** XML attribute or element name of a {@link #getNode} property. */ + private static final String NODE__XML_ATTR = "node"; + + /** XML attribute or element name of a {@link #getNodes} property. */ + private static final String NODES__XML_ATTR = "nodes"; + + @Override + public String getXmlTagName() { + return LEVEL_1__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasNode()) { + out.writeStartElement(NODE__XML_ATTR); + getNode().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(NODES__XML_ATTR); + for (test.nested.data.Level1.Level2.Node element : getNodes()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.data.Level1} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Level1_Impl readLevel1_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Level1_Impl result = new Level1_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NODE__XML_ATTR: { + in.nextTag(); + setNode(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.readNode_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case NODES__XML_ATTR: { + internalReadNodesListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadNodesListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addNodes(test.nested.data.impl.Level1_Impl.Level2_Impl.Node_Impl.readNode_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Outer_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Outer_Impl.java new file mode 100644 index 00000000..1eccdcb5 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Outer_Impl.java @@ -0,0 +1,1301 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Outer}. + */ +public class Outer_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Outer { + /** + * Implementation of {@link test.nested.data.Outer.Shape}. + */ + public static abstract class Shape_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Outer.Shape { + + private String _name = ""; + + /** + * Creates a {@link Shape_Impl} instance. + */ + public Shape_Impl() { + super(); + } + + @Override + public final String getName() { + return _name; + } + + @Override + public test.nested.data.Outer.Shape setName(String value) { + internalSetName(value); + return this; + } + + /** Internal setter for {@link #getName()} without chain call utility. */ + protected final void internalSetName(String value) { + _listener.beforeSet(this, NAME__PROP, value); + _name = value; + _listener.afterChanged(this, NAME__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Outer.Shape registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Outer.Shape unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NAME__PROP: return getName(); + default: return test.nested.data.Outer.Shape.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NAME__PROP: internalSetName((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NAME__PROP); + out.value(getName()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + out.name(0); + out.value(typeId()); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(NAME__ID); + out.value(getName()); + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case NAME__ID: setName(in.nextString()); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Outer.Shape} type. */ + public static final String SHAPE__XML_ELEMENT = "shape"; + + /** XML attribute or element name of a {@link #getName} property. */ + private static final String NAME__XML_ATTR = "name"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NAME__XML_ATTR, getName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.data.Outer.Shape} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shape_Impl readShape_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.data.impl.Outer_Impl.Circle_Impl.CIRCLE__XML_ELEMENT: { + return test.nested.data.impl.Outer_Impl.Circle_Impl.readCircle_XmlContent(in); + } + + case test.nested.data.impl.Outer_Impl.Square_Impl.SQUARE__XML_ELEMENT: { + return test.nested.data.impl.Outer_Impl.Square_Impl.readSquare_XmlContent(in); + } + + case Triangle_Impl.TRIANGLE__XML_ELEMENT: { + return test.nested.data.impl.Triangle_Impl.readTriangle_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NAME__XML_ATTR: { + setName(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NAME__XML_ATTR: { + setName(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + /** + * Implementation of {@link test.nested.data.Outer.Circle}. + */ + public static class Circle_Impl extends test.nested.data.impl.Outer_Impl.Shape_Impl implements test.nested.data.Outer.Circle { + + private int _radius = 0; + + /** + * Creates a {@link Circle_Impl} instance. + * + * @see test.nested.data.Outer.Circle#create() + */ + public Circle_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.CIRCLE; + } + + @Override + public final int getRadius() { + return _radius; + } + + @Override + public test.nested.data.Outer.Circle setRadius(int value) { + internalSetRadius(value); + return this; + } + + /** Internal setter for {@link #getRadius()} without chain call utility. */ + protected final void internalSetRadius(int value) { + _listener.beforeSet(this, RADIUS__PROP, value); + _radius = value; + _listener.afterChanged(this, RADIUS__PROP); + } + + @Override + public test.nested.data.Outer.Circle setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return CIRCLE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + RADIUS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case RADIUS__PROP: return getRadius(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case RADIUS__PROP: internalSetRadius((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(RADIUS__PROP); + out.value(getRadius()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case RADIUS__PROP: setRadius(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return CIRCLE__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(RADIUS__ID); + out.value(getRadius()); + } + + /** Helper for creating an object of type {@link test.nested.data.Outer.Circle} from a polymorphic composition. */ + public static test.nested.data.Outer.Circle readCircle_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Circle_Impl result = new Circle_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case RADIUS__ID: setRadius(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Outer.Circle} type. */ + public static final String CIRCLE__XML_ELEMENT = "circle"; + + /** XML attribute or element name of a {@link #getRadius} property. */ + private static final String RADIUS__XML_ATTR = "radius"; + + @Override + public String getXmlTagName() { + return CIRCLE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(RADIUS__XML_ATTR, Integer.toString(getRadius())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Outer.Circle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Circle_Impl readCircle_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Circle_Impl result = new Circle_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case RADIUS__XML_ATTR: { + setRadius(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case RADIUS__XML_ATTR: { + setRadius(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Outer.Shape.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Outer.Square}. + */ + public static class Square_Impl extends test.nested.data.impl.Outer_Impl.Shape_Impl implements test.nested.data.Outer.Square { + + private int _side = 0; + + /** + * Creates a {@link Square_Impl} instance. + * + * @see test.nested.data.Outer.Square#create() + */ + public Square_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.SQUARE; + } + + @Override + public final int getSide() { + return _side; + } + + @Override + public test.nested.data.Outer.Square setSide(int value) { + internalSetSide(value); + return this; + } + + /** Internal setter for {@link #getSide()} without chain call utility. */ + protected final void internalSetSide(int value) { + _listener.beforeSet(this, SIDE__PROP, value); + _side = value; + _listener.afterChanged(this, SIDE__PROP); + } + + @Override + public test.nested.data.Outer.Square setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return SQUARE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SIDE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SIDE__PROP: return getSide(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SIDE__PROP: internalSetSide((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SIDE__PROP); + out.value(getSide()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SIDE__PROP: setSide(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return SQUARE__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SIDE__ID); + out.value(getSide()); + } + + /** Helper for creating an object of type {@link test.nested.data.Outer.Square} from a polymorphic composition. */ + public static test.nested.data.Outer.Square readSquare_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Square_Impl result = new Square_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case SIDE__ID: setSide(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Outer.Square} type. */ + public static final String SQUARE__XML_ELEMENT = "square"; + + /** XML attribute or element name of a {@link #getSide} property. */ + private static final String SIDE__XML_ATTR = "side"; + + @Override + public String getXmlTagName() { + return SQUARE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(SIDE__XML_ATTR, Integer.toString(getSide())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Outer.Square} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Square_Impl readSquare_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Square_Impl result = new Square_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case SIDE__XML_ATTR: { + setSide(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SIDE__XML_ATTR: { + setSide(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Outer.Shape.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Outer.Drawing}. + */ + public static class Drawing_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Outer.Drawing { + + private test.nested.data.Outer.Shape _main = null; + + private final java.util.List _shapes = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Outer.Shape element) { + _listener.beforeAdd(Drawing_Impl.this, SHAPES__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Outer.Shape element) { + _listener.afterRemove(Drawing_Impl.this, SHAPES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Drawing_Impl.this, SHAPES__PROP); + } + }; + + /** + * Creates a {@link Drawing_Impl} instance. + * + * @see test.nested.data.Outer.Drawing#create() + */ + public Drawing_Impl() { + super(); + } + + @Override + public final test.nested.data.Outer.Shape getMain() { + return _main; + } + + @Override + public test.nested.data.Outer.Drawing setMain(test.nested.data.Outer.Shape value) { + internalSetMain(value); + return this; + } + + /** Internal setter for {@link #getMain()} without chain call utility. */ + protected final void internalSetMain(test.nested.data.Outer.Shape value) { + _listener.beforeSet(this, MAIN__PROP, value); + _main = value; + _listener.afterChanged(this, MAIN__PROP); + } + + @Override + public final boolean hasMain() { + return _main != null; + } + + @Override + public final java.util.List getShapes() { + return _shapes; + } + + @Override + public test.nested.data.Outer.Drawing setShapes(java.util.List value) { + internalSetShapes(value); + return this; + } + + /** Internal setter for {@link #getShapes()} without chain call utility. */ + protected final void internalSetShapes(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'shapes' cannot be null."); + _shapes.clear(); + _shapes.addAll(value); + } + + @Override + public test.nested.data.Outer.Drawing addShape(test.nested.data.Outer.Shape value) { + internalAddShape(value); + return this; + } + + /** Implementation of {@link #addShape(test.nested.data.Outer.Shape)} without chain call utility. */ + protected final void internalAddShape(test.nested.data.Outer.Shape value) { + _shapes.add(value); + } + + @Override + public final void removeShape(test.nested.data.Outer.Shape value) { + _shapes.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Outer.Drawing registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Outer.Drawing unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return DRAWING__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + MAIN__PROP, + SHAPES__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case MAIN__PROP: return getMain(); + case SHAPES__PROP: return getShapes(); + default: return test.nested.data.Outer.Drawing.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case MAIN__PROP: internalSetMain((test.nested.data.Outer.Shape) value); break; + case SHAPES__PROP: internalSetShapes(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Outer.Shape.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasMain()) { + out.name(MAIN__PROP); + getMain().writeTo(out); + } + out.name(SHAPES__PROP); + out.beginArray(); + for (test.nested.data.Outer.Shape x : getShapes()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case MAIN__PROP: setMain(test.nested.data.Outer.Shape.readShape(in)); break; + case SHAPES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Outer.Shape.readShape(in)); + } + in.endArray(); + setShapes(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasMain()) { + out.name(MAIN__ID); + getMain().writeTo(out); + } + out.name(SHAPES__ID); + { + java.util.List values = getShapes(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Outer.Shape x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Outer.Drawing} from a polymorphic composition. */ + public static test.nested.data.Outer.Drawing readDrawing_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl.Drawing_Impl result = new Drawing_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case MAIN__ID: setMain(test.nested.data.Outer.Shape.readShape(in)); break; + case SHAPES__ID: { + in.beginArray(); + while (in.hasNext()) { + addShape(test.nested.data.Outer.Shape.readShape(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Outer.Drawing} type. */ + public static final String DRAWING__XML_ELEMENT = "drawing"; + + /** XML attribute or element name of a {@link #getMain} property. */ + private static final String MAIN__XML_ATTR = "main"; + + /** XML attribute or element name of a {@link #getShapes} property. */ + private static final String SHAPES__XML_ATTR = "shapes"; + + @Override + public String getXmlTagName() { + return DRAWING__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasMain()) { + out.writeStartElement(MAIN__XML_ATTR); + getMain().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(SHAPES__XML_ATTR); + for (test.nested.data.Outer.Shape element : getShapes()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.data.Outer.Drawing} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Drawing_Impl readDrawing_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Drawing_Impl result = new Drawing_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case MAIN__XML_ATTR: { + in.nextTag(); + setMain(test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case SHAPES__XML_ATTR: { + internalReadShapesListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadShapesListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addShape(test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in)); + } + } + + } + + private test.nested.data.Outer.Shape _shape = null; + + /** + * Creates a {@link Outer_Impl} instance. + * + * @see test.nested.data.Outer#create() + */ + public Outer_Impl() { + super(); + } + + @Override + public final test.nested.data.Outer.Shape getShape() { + return _shape; + } + + @Override + public test.nested.data.Outer setShape(test.nested.data.Outer.Shape value) { + internalSetShape(value); + return this; + } + + /** Internal setter for {@link #getShape()} without chain call utility. */ + protected final void internalSetShape(test.nested.data.Outer.Shape value) { + _listener.beforeSet(this, SHAPE__PROP, value); + _shape = value; + _listener.afterChanged(this, SHAPE__PROP); + } + + @Override + public final boolean hasShape() { + return _shape != null; + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Outer registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Outer unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return OUTER__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SHAPE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SHAPE__PROP: return getShape(); + default: return test.nested.data.Outer.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SHAPE__PROP: internalSetShape((test.nested.data.Outer.Shape) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasShape()) { + out.name(SHAPE__PROP); + getShape().writeTo(out); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SHAPE__PROP: setShape(test.nested.data.Outer.Shape.readShape(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasShape()) { + out.name(SHAPE__ID); + getShape().writeTo(out); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Outer} from a polymorphic composition. */ + public static test.nested.data.Outer readOuter_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Outer_Impl result = new Outer_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case SHAPE__ID: setShape(test.nested.data.Outer.Shape.readShape(in)); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Outer} type. */ + public static final String OUTER__XML_ELEMENT = "outer"; + + /** XML attribute or element name of a {@link #getShape} property. */ + private static final String SHAPE__XML_ATTR = "shape"; + + @Override + public String getXmlTagName() { + return OUTER__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasShape()) { + out.writeStartElement(SHAPE__XML_ATTR); + getShape().writeTo(out); + out.writeEndElement(); + } + } + + /** Creates a new {@link test.nested.data.Outer} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Outer_Impl readOuter_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Outer_Impl result = new Outer_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SHAPE__XML_ATTR: { + in.nextTag(); + setShape(test.nested.data.impl.Outer_Impl.Shape_Impl.readShape_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Triangle_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Triangle_Impl.java new file mode 100644 index 00000000..64a87441 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Triangle_Impl.java @@ -0,0 +1,246 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Triangle}. + */ +public class Triangle_Impl extends test.nested.data.impl.Outer_Impl.Shape_Impl implements test.nested.data.Triangle { + + private int _base = 0; + + private int _height = 0; + + /** + * Creates a {@link Triangle_Impl} instance. + * + * @see test.nested.data.Triangle#create() + */ + public Triangle_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.TRIANGLE; + } + + @Override + public final int getBase() { + return _base; + } + + @Override + public test.nested.data.Triangle setBase(int value) { + internalSetBase(value); + return this; + } + + /** Internal setter for {@link #getBase()} without chain call utility. */ + protected final void internalSetBase(int value) { + _listener.beforeSet(this, BASE__PROP, value); + _base = value; + _listener.afterChanged(this, BASE__PROP); + } + + @Override + public final int getHeight() { + return _height; + } + + @Override + public test.nested.data.Triangle setHeight(int value) { + internalSetHeight(value); + return this; + } + + /** Internal setter for {@link #getHeight()} without chain call utility. */ + protected final void internalSetHeight(int value) { + _listener.beforeSet(this, HEIGHT__PROP, value); + _height = value; + _listener.afterChanged(this, HEIGHT__PROP); + } + + @Override + public test.nested.data.Triangle setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return TRIANGLE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + BASE__PROP, + HEIGHT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Outer_Impl.Shape_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case BASE__PROP: return getBase(); + case HEIGHT__PROP: return getHeight(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case BASE__PROP: internalSetBase((int) value); break; + case HEIGHT__PROP: internalSetHeight((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(BASE__PROP); + out.value(getBase()); + out.name(HEIGHT__PROP); + out.value(getHeight()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case BASE__PROP: setBase(in.nextInt()); break; + case HEIGHT__PROP: setHeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return TRIANGLE__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(BASE__ID); + out.value(getBase()); + out.name(HEIGHT__ID); + out.value(getHeight()); + } + + /** Helper for creating an object of type {@link test.nested.data.Triangle} from a polymorphic composition. */ + public static test.nested.data.Triangle readTriangle_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Triangle_Impl result = new Triangle_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case BASE__ID: setBase(in.nextInt()); break; + case HEIGHT__ID: setHeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Triangle} type. */ + public static final String TRIANGLE__XML_ELEMENT = "triangle"; + + /** XML attribute or element name of a {@link #getBase} property. */ + private static final String BASE__XML_ATTR = "base"; + + /** XML attribute or element name of a {@link #getHeight} property. */ + private static final String HEIGHT__XML_ATTR = "height"; + + @Override + public String getXmlTagName() { + return TRIANGLE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(BASE__XML_ATTR, Integer.toString(getBase())); + out.writeAttribute(HEIGHT__XML_ATTR, Integer.toString(getHeight())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Triangle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Triangle_Impl readTriangle_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Triangle_Impl result = new Triangle_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case BASE__XML_ATTR: { + setBase(Integer.parseInt(value)); + break; + } + case HEIGHT__XML_ATTR: { + setHeight(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case BASE__XML_ATTR: { + setBase(Integer.parseInt(in.getElementText())); + break; + } + case HEIGHT__XML_ATTR: { + setHeight(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Outer.Shape.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Zoo_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Zoo_Impl.java new file mode 100644 index 00000000..83c78376 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/data/impl/Zoo_Impl.java @@ -0,0 +1,974 @@ +package test.nested.data.impl; + +/** + * Implementation of {@link test.nested.data.Zoo}. + */ +public class Zoo_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.data.Zoo { + /** + * Implementation of {@link test.nested.data.Zoo.Cat}. + */ + public static class Cat_Impl extends test.nested.data.impl.Animal_Impl implements test.nested.data.Zoo.Cat { + + private boolean _indoor = false; + + /** + * Creates a {@link Cat_Impl} instance. + * + * @see test.nested.data.Zoo.Cat#create() + */ + public Cat_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.CAT; + } + + @Override + public final boolean isIndoor() { + return _indoor; + } + + @Override + public test.nested.data.Zoo.Cat setIndoor(boolean value) { + internalSetIndoor(value); + return this; + } + + /** Internal setter for {@link #isIndoor()} without chain call utility. */ + protected final void internalSetIndoor(boolean value) { + _listener.beforeSet(this, INDOOR__PROP, value); + _indoor = value; + _listener.afterChanged(this, INDOOR__PROP); + } + + @Override + public test.nested.data.Zoo.Cat setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return CAT__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + INDOOR__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Animal_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Animal_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case INDOOR__PROP: return isIndoor(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case INDOOR__PROP: internalSetIndoor((boolean) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(INDOOR__PROP); + out.value(isIndoor()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case INDOOR__PROP: setIndoor(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return CAT__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(INDOOR__ID); + out.value(isIndoor()); + } + + /** Helper for creating an object of type {@link test.nested.data.Zoo.Cat} from a polymorphic composition. */ + public static test.nested.data.Zoo.Cat readCat_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl.Cat_Impl result = new Cat_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case INDOOR__ID: setIndoor(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Zoo.Cat} type. */ + public static final String CAT__XML_ELEMENT = "cat"; + + /** XML attribute or element name of a {@link #isIndoor} property. */ + private static final String INDOOR__XML_ATTR = "indoor"; + + @Override + public String getXmlTagName() { + return CAT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(INDOOR__XML_ATTR, Boolean.toString(isIndoor())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Zoo.Cat} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Cat_Impl readCat_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Cat_Impl result = new Cat_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case INDOOR__XML_ATTR: { + setIndoor(Boolean.parseBoolean(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case INDOOR__XML_ATTR: { + setIndoor(Boolean.parseBoolean(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Animal.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Zoo.Bird}. + */ + public static abstract class Bird_Impl extends test.nested.data.impl.Animal_Impl implements test.nested.data.Zoo.Bird { + + private double _wingspan = 0.0d; + + /** + * Creates a {@link Bird_Impl} instance. + */ + public Bird_Impl() { + super(); + } + + @Override + public final double getWingspan() { + return _wingspan; + } + + @Override + public test.nested.data.Zoo.Bird setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + /** Internal setter for {@link #getWingspan()} without chain call utility. */ + protected final void internalSetWingspan(double value) { + _listener.beforeSet(this, WINGSPAN__PROP, value); + _wingspan = value; + _listener.afterChanged(this, WINGSPAN__PROP); + } + + @Override + public test.nested.data.Zoo.Bird setName(String value) { + internalSetName(value); + return this; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WINGSPAN__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Animal_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Animal_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WINGSPAN__PROP: return getWingspan(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WINGSPAN__PROP: internalSetWingspan((double) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WINGSPAN__PROP); + out.value(getWingspan()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WINGSPAN__PROP: setWingspan(in.nextDouble()); break; + default: super.readField(in, field); + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WINGSPAN__ID); + out.value(getWingspan()); + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case WINGSPAN__ID: setWingspan(in.nextDouble()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Zoo.Bird} type. */ + public static final String BIRD__XML_ELEMENT = "bird"; + + /** XML attribute or element name of a {@link #getWingspan} property. */ + private static final String WINGSPAN__XML_ATTR = "wingspan"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WINGSPAN__XML_ATTR, Double.toString(getWingspan())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Zoo.Bird} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Bird_Impl readBird_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.data.impl.Zoo_Impl.Parrot_Impl.PARROT__XML_ELEMENT: { + return test.nested.data.impl.Zoo_Impl.Parrot_Impl.readParrot_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WINGSPAN__XML_ATTR: { + setWingspan(Double.parseDouble(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WINGSPAN__XML_ATTR: { + setWingspan(Double.parseDouble(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.nested.data.Animal.Visitor v, A arg) throws E { + return visit((test.nested.data.Zoo.Bird.Visitor) v, arg); + } + + } + /** + * Implementation of {@link test.nested.data.Zoo.Parrot}. + */ + public static class Parrot_Impl extends test.nested.data.impl.Zoo_Impl.Bird_Impl implements test.nested.data.Zoo.Parrot { + + private final java.util.List _words = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, String element) { + _listener.beforeAdd(Parrot_Impl.this, WORDS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, String element) { + _listener.afterRemove(Parrot_Impl.this, WORDS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Parrot_Impl.this, WORDS__PROP); + } + }; + + /** + * Creates a {@link Parrot_Impl} instance. + * + * @see test.nested.data.Zoo.Parrot#create() + */ + public Parrot_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.PARROT; + } + + @Override + public final java.util.List getWords() { + return _words; + } + + @Override + public test.nested.data.Zoo.Parrot setWords(java.util.List value) { + internalSetWords(value); + return this; + } + + /** Internal setter for {@link #getWords()} without chain call utility. */ + protected final void internalSetWords(java.util.List value) { + _words.clear(); + _words.addAll(value); + } + + @Override + public test.nested.data.Zoo.Parrot addWord(String value) { + internalAddWord(value); + return this; + } + + /** Implementation of {@link #addWord(String)} without chain call utility. */ + protected final void internalAddWord(String value) { + _words.add(value); + } + + @Override + public final void removeWord(String value) { + _words.remove(value); + } + + @Override + public test.nested.data.Zoo.Parrot setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + @Override + public test.nested.data.Zoo.Parrot setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return PARROT__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WORDS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.data.impl.Zoo_Impl.Bird_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.data.impl.Zoo_Impl.Bird_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WORDS__PROP: return getWords(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WORDS__PROP: internalSetWords(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WORDS__PROP); + out.beginArray(); + for (String x : getWords()) { + out.value(x); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WORDS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); + } + in.endArray(); + setWords(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return PARROT__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WORDS__ID); + { + java.util.List values = getWords(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.STRING, values.size()); + for (String x : values) { + out.value(x); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Zoo.Parrot} from a polymorphic composition. */ + public static test.nested.data.Zoo.Parrot readParrot_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl.Parrot_Impl result = new Parrot_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case WORDS__ID: { + in.beginArray(); + while (in.hasNext()) { + addWord(in.nextString()); + } + in.endArray(); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.data.Zoo.Parrot} type. */ + public static final String PARROT__XML_ELEMENT = "parrot"; + + /** XML attribute or element name of a {@link #getWords} property. */ + private static final String WORDS__XML_ATTR = "words"; + + @Override + public String getXmlTagName() { + return PARROT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WORDS__XML_ATTR, getWords().stream().map(x -> x).collect(java.util.stream.Collectors.joining(", "))); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.data.Zoo.Parrot} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Parrot_Impl readParrot_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Parrot_Impl result = new Parrot_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WORDS__XML_ATTR: { + setWords(java.util.Arrays.stream(value.split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WORDS__XML_ATTR: { + setWords(java.util.Arrays.stream(in.getElementText().split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.data.Zoo.Bird.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + private final java.util.List _animals = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.data.Animal element) { + _listener.beforeAdd(Zoo_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.data.Animal element) { + _listener.afterRemove(Zoo_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Zoo_Impl.this, ANIMALS__PROP); + } + }; + + /** + * Creates a {@link Zoo_Impl} instance. + * + * @see test.nested.data.Zoo#create() + */ + public Zoo_Impl() { + super(); + } + + @Override + public final java.util.List getAnimals() { + return _animals; + } + + @Override + public test.nested.data.Zoo setAnimals(java.util.List value) { + internalSetAnimals(value); + return this; + } + + /** Internal setter for {@link #getAnimals()} without chain call utility. */ + protected final void internalSetAnimals(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'animals' cannot be null."); + _animals.clear(); + _animals.addAll(value); + } + + @Override + public test.nested.data.Zoo addAnimal(test.nested.data.Animal value) { + internalAddAnimal(value); + return this; + } + + /** Implementation of {@link #addAnimal(test.nested.data.Animal)} without chain call utility. */ + protected final void internalAddAnimal(test.nested.data.Animal value) { + _animals.add(value); + } + + @Override + public final void removeAnimal(test.nested.data.Animal value) { + _animals.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.data.Zoo registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.data.Zoo unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return ZOO__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + ANIMALS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case ANIMALS__PROP: return getAnimals(); + default: return test.nested.data.Zoo.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case ANIMALS__PROP: internalSetAnimals(de.haumacher.msgbuf.util.Conversions.asList(test.nested.data.Animal.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(ANIMALS__PROP); + out.beginArray(); + for (test.nested.data.Animal x : getAnimals()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case ANIMALS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.data.Animal.readAnimal(in)); + } + in.endArray(); + setAnimals(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(ANIMALS__ID); + { + java.util.List values = getAnimals(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.data.Animal x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.data.Zoo} from a polymorphic composition. */ + public static test.nested.data.Zoo readZoo_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.data.impl.Zoo_Impl result = new Zoo_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case ANIMALS__ID: { + in.beginArray(); + while (in.hasNext()) { + addAnimal(test.nested.data.Animal.readAnimal(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.data.Zoo} type. */ + public static final String ZOO__XML_ELEMENT = "zoo"; + + /** XML attribute or element name of a {@link #getAnimals} property. */ + private static final String ANIMALS__XML_ATTR = "animals"; + + @Override + public String getXmlTagName() { + return ZOO__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeStartElement(ANIMALS__XML_ATTR); + for (test.nested.data.Animal element : getAnimals()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.data.Zoo} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Zoo_Impl readZoo_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Zoo_Impl result = new Zoo_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case ANIMALS__XML_ATTR: { + internalReadAnimalsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadAnimalsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addAnimal(test.nested.data.impl.Animal_Impl.readAnimal_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Doc.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Doc.java new file mode 100644 index 00000000..2b900744 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Doc.java @@ -0,0 +1,522 @@ +package test.nested.doc; + +/** + * A hierarchy nested two levels deep with an abstract intermediate, a nested enum, a reserved-word + * property and message name, and fields holding it as repeated, map and nullable values (issue #16). + */ +public interface Doc extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Sec extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Item extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.doc.Doc.Sec.Item} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.doc.Doc.Sec.Para}. */ + PARA, + + /** Type literal for {@link test.nested.doc.Doc.Sec.Case}. */ + CASE, + + /** Type literal for {@link test.nested.doc.Figure}. */ + FIGURE, + ; + + } + + /** Visitor interface for the {@link test.nested.doc.Doc.Sec.Item} hierarchy.*/ + public interface Visitor extends test.nested.doc.Doc.Sec.Block.Visitor { + + // Pure sum interface. + + } + + public enum Kind implements de.haumacher.msgbuf.data.ProtocolEnum { + + PLAIN("PLAIN"), + + RICH("RICH"), + + ; + + private final String _protocolName; + + private Kind(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link Kind} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link Kind} constant by it's protocol name. */ + public static Kind valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "PLAIN": return PLAIN; + case "RICH": return RICH; + } + return PLAIN; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static Kind readKind(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } + + /** Writes this instance to the given binary output. */ + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + switch (this) { + case PLAIN: out.value(1); break; + case RICH: out.value(2); break; + default: out.value(0); + } + } + + /** Reads a new instance from the given binary reader. */ + public static Kind readKind(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + switch (in.nextInt()) { + case 1: return PLAIN; + case 2: return RICH; + default: return PLAIN; + } + } + } + + /** @see #getKind() */ + String KIND__PROP = "kind"; + + /** @see #getPackage() */ + String PACKAGE__PROP = "package"; + + /** Identifier for the property {@link #getKind()} in binary format. */ + static final int KIND__ID = 1; + + /** Identifier for the property {@link #getPackage()} in binary format. */ + static final int PACKAGE__ID = 2; + + /** The type code of this instance. */ + TypeKind kind(); + + test.nested.doc.Doc.Sec.Item.Kind getKind(); + + /** + * @see #getKind() + */ + test.nested.doc.Doc.Sec.Item setKind(test.nested.doc.Doc.Sec.Item.Kind value); + + String getPackage(); + + /** + * @see #getPackage() + */ + test.nested.doc.Doc.Sec.Item setPackage(String value); + + @Override + public test.nested.doc.Doc.Sec.Item registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.doc.Doc.Sec.Item unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Item readItem(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.Doc.Sec.Item result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.doc.Doc.Sec.Para.PARA__TYPE: result = test.nested.doc.Doc.Sec.Para.readPara(in); break; + case test.nested.doc.Doc.Sec.Case.CASE__TYPE: result = test.nested.doc.Doc.Sec.Case.readCase(in); break; + case Figure.FIGURE__TYPE: result = test.nested.doc.Figure.readFigure(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** The binary identifier for this concrete type in the polymorphic {@link test.nested.doc.Doc.Sec.Item} hierarchy. */ + abstract int typeId(); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Item readItem(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.doc.Doc.Sec.Item result; + switch (type) { + case test.nested.doc.Doc.Sec.Para.PARA__TYPE_ID: result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_Content(in); break; + case test.nested.doc.Doc.Sec.Case.CASE__TYPE_ID: result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_Content(in); break; + case test.nested.doc.Figure.FIGURE__TYPE_ID: result = test.nested.doc.impl.Figure_Impl.readFigure_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Item} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Item readItem(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Block extends test.nested.doc.Doc.Sec.Item { + + /** Visitor interface for the {@link test.nested.doc.Doc.Sec.Block} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.doc.Doc.Sec.Para}.*/ + R visit(test.nested.doc.Doc.Sec.Para self, A arg) throws E; + + /** Visit case for {@link test.nested.doc.Doc.Sec.Case}.*/ + R visit(test.nested.doc.Doc.Sec.Case self, A arg) throws E; + + /** Visit case for {@link test.nested.doc.Figure}.*/ + R visit(test.nested.doc.Figure self, A arg) throws E; + + } + + /** @see #getWeight() */ + String WEIGHT__PROP = "weight"; + + /** Identifier for the property {@link #getWeight()} in binary format. */ + static final int WEIGHT__ID = 3; + + int getWeight(); + + /** + * @see #getWeight() + */ + test.nested.doc.Doc.Sec.Block setWeight(int value); + + @Override + test.nested.doc.Doc.Sec.Block setKind(test.nested.doc.Doc.Sec.Item.Kind value); + + @Override + test.nested.doc.Doc.Sec.Block setPackage(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Block readBlock(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.Doc.Sec.Block result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.doc.Doc.Sec.Para.PARA__TYPE: result = test.nested.doc.Doc.Sec.Para.readPara(in); break; + case test.nested.doc.Doc.Sec.Case.CASE__TYPE: result = test.nested.doc.Doc.Sec.Case.readCase(in); break; + case Figure.FIGURE__TYPE: result = test.nested.doc.Figure.readFigure(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Block readBlock(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.doc.Doc.Sec.Block result; + switch (type) { + case test.nested.doc.Doc.Sec.Para.PARA__TYPE_ID: result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_Content(in); break; + case test.nested.doc.Doc.Sec.Case.CASE__TYPE_ID: result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_Content(in); break; + case test.nested.doc.Figure.FIGURE__TYPE_ID: result = test.nested.doc.impl.Figure_Impl.readFigure_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Block} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Block readBlock(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.readBlock_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Para extends test.nested.doc.Doc.Sec.Block { + + /** + * Creates a {@link test.nested.doc.Doc.Sec.Para} instance. + */ + static test.nested.doc.Doc.Sec.Para create() { + return new test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl(); + } + + /** Identifier for the {@link test.nested.doc.Doc.Sec.Para} type in JSON format. */ + String PARA__TYPE = "Para"; + + /** @see #getText() */ + String TEXT__PROP = "text"; + + /** Identifier for the {@link test.nested.doc.Doc.Sec.Para} type in binary format. */ + static final int PARA__TYPE_ID = 1; + + /** Identifier for the property {@link #getText()} in binary format. */ + static final int TEXT__ID = 4; + + String getText(); + + /** + * @see #getText() + */ + test.nested.doc.Doc.Sec.Para setText(String value); + + @Override + test.nested.doc.Doc.Sec.Para setWeight(int value); + + @Override + test.nested.doc.Doc.Sec.Para setKind(test.nested.doc.Doc.Sec.Item.Kind value); + + @Override + test.nested.doc.Doc.Sec.Para setPackage(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Para readPara(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl result = new test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Para readPara(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.doc.Doc.Sec.Para result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Para} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Para readPara(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_XmlContent(in); + } + + } + public interface Case extends test.nested.doc.Doc.Sec.Block { + + /** + * Creates a {@link test.nested.doc.Doc.Sec.Case} instance. + */ + static test.nested.doc.Doc.Sec.Case create() { + return new test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl(); + } + + /** Identifier for the {@link test.nested.doc.Doc.Sec.Case} type in JSON format. */ + String CASE__TYPE = "Case"; + + /** @see #getChildren() */ + String CHILDREN__PROP = "children"; + + /** Identifier for the {@link test.nested.doc.Doc.Sec.Case} type in binary format. */ + static final int CASE__TYPE_ID = 2; + + /** Identifier for the property {@link #getChildren()} in binary format. */ + static final int CHILDREN__ID = 4; + + java.util.List getChildren(); + + /** + * @see #getChildren() + */ + test.nested.doc.Doc.Sec.Case setChildren(java.util.List value); + + /** + * Adds a value to the {@link #getChildren()} list. + */ + test.nested.doc.Doc.Sec.Case addChildren(test.nested.doc.Doc.Sec.Item value); + + /** + * Removes a value from the {@link #getChildren()} list. + */ + void removeChildren(test.nested.doc.Doc.Sec.Item value); + + @Override + test.nested.doc.Doc.Sec.Case setWeight(int value); + + @Override + test.nested.doc.Doc.Sec.Case setKind(test.nested.doc.Doc.Sec.Item.Kind value); + + @Override + test.nested.doc.Doc.Sec.Case setPackage(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Case readCase(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl result = new test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec.Case readCase(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.doc.Doc.Sec.Case result = test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Case} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Case readCase(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.doc.Doc.Sec} instance. + */ + static test.nested.doc.Doc.Sec create() { + return new test.nested.doc.impl.Doc_Impl.Sec_Impl(); + } + + /** Identifier for the {@link test.nested.doc.Doc.Sec} type in JSON format. */ + String SEC__TYPE = "Sec"; + + @Override + public test.nested.doc.Doc.Sec registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.doc.Doc.Sec unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec readSec(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl result = new test.nested.doc.impl.Doc_Impl.Sec_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc.Sec readSec(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.doc.Doc.Sec result = test.nested.doc.impl.Doc_Impl.Sec_Impl.readSec_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Sec} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sec readSec(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.Sec_Impl.readSec_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.doc.Doc} instance. + */ + static test.nested.doc.Doc create() { + return new test.nested.doc.impl.Doc_Impl(); + } + + /** Identifier for the {@link test.nested.doc.Doc} type in JSON format. */ + String DOC__TYPE = "Doc"; + + /** @see #getItems() */ + String ITEMS__PROP = "items"; + + /** @see #getByName() */ + String BY_NAME__PROP = "byName"; + + /** @see #getMaybe() */ + String MAYBE__PROP = "maybe"; + + /** Identifier for the property {@link #getItems()} in binary format. */ + static final int ITEMS__ID = 1; + + /** Identifier for the property {@link #getByName()} in binary format. */ + static final int BY_NAME__ID = 2; + + /** Identifier for the property {@link #getMaybe()} in binary format. */ + static final int MAYBE__ID = 3; + + java.util.List getItems(); + + /** + * @see #getItems() + */ + test.nested.doc.Doc setItems(java.util.List value); + + /** + * Adds a value to the {@link #getItems()} list. + */ + test.nested.doc.Doc addItem(test.nested.doc.Doc.Sec.Item value); + + /** + * Removes a value from the {@link #getItems()} list. + */ + void removeItem(test.nested.doc.Doc.Sec.Item value); + + java.util.Map getByName(); + + /** + * @see #getByName() + */ + test.nested.doc.Doc setByName(java.util.Map value); + + /** + * Adds a key value pair to the {@link #getByName()} map. + */ + test.nested.doc.Doc putByName(String key, test.nested.doc.Doc.Sec.Item value); + + /** + * Removes a key from the {@link #getByName()} map. + */ + void removeByName(String key); + + test.nested.doc.Doc.Sec.Item getMaybe(); + + /** + * @see #getMaybe() + */ + test.nested.doc.Doc setMaybe(test.nested.doc.Doc.Sec.Item value); + + /** + * Checks, whether {@link #getMaybe()} has a value. + */ + boolean hasMaybe(); + + @Override + public test.nested.doc.Doc registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.doc.Doc unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc readDoc(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl result = new test.nested.doc.impl.Doc_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Doc readDoc(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.doc.Doc result = test.nested.doc.impl.Doc_Impl.readDoc_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Doc} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Doc readDoc(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Doc_Impl.readDoc_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Figure.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Figure.java new file mode 100644 index 00000000..75e0a679 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/Figure.java @@ -0,0 +1,64 @@ +package test.nested.doc; + +/** + * A top-level specialization of a nested abstract intermediate. + */ +public interface Figure extends test.nested.doc.Doc.Sec.Block { + + /** + * Creates a {@link test.nested.doc.Figure} instance. + */ + static test.nested.doc.Figure create() { + return new test.nested.doc.impl.Figure_Impl(); + } + + /** Identifier for the {@link test.nested.doc.Figure} type in JSON format. */ + String FIGURE__TYPE = "Figure"; + + /** @see #getSrc() */ + String SRC__PROP = "src"; + + /** Identifier for the {@link test.nested.doc.Figure} type in binary format. */ + static final int FIGURE__TYPE_ID = 3; + + /** Identifier for the property {@link #getSrc()} in binary format. */ + static final int SRC__ID = 4; + + String getSrc(); + + /** + * @see #getSrc() + */ + test.nested.doc.Figure setSrc(String value); + + @Override + test.nested.doc.Figure setWeight(int value); + + @Override + test.nested.doc.Figure setKind(test.nested.doc.Doc.Sec.Item.Kind value); + + @Override + test.nested.doc.Figure setPackage(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Figure readFigure(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.doc.impl.Figure_Impl result = new test.nested.doc.impl.Figure_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.doc.Figure readFigure(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.doc.Figure result = test.nested.doc.impl.Figure_Impl.readFigure_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Figure} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Figure readFigure(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.doc.impl.Figure_Impl.readFigure_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/doc.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/doc.proto new file mode 100644 index 00000000..407ecab6 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/doc.proto @@ -0,0 +1,32 @@ +package test.nested.doc; + +/** + * A hierarchy nested two levels deep with an abstract intermediate, a nested enum, a reserved-word + * property and message name, and fields holding it as repeated, map and nullable values (issue #16). + */ +message Doc { + message Sec { + abstract message Item { + enum Kind { PLAIN; RICH; } + Kind kind; + string `package`; + } + abstract message Block extends Item { + int weight; + } + message Para extends Block { + string text; + } + message `Case` extends Block { + repeated Item children; + } + } + repeated Sec.Item items; + map byName; + @Nullable Sec.Item maybe; +} + +/** A top-level specialization of a nested abstract intermediate. */ +message Figure extends Doc.Sec.Block { + string src; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Doc_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Doc_Impl.java new file mode 100644 index 00000000..75a80d96 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Doc_Impl.java @@ -0,0 +1,1640 @@ +package test.nested.doc.impl; + +/** + * Implementation of {@link test.nested.doc.Doc}. + */ +public class Doc_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.doc.Doc { + /** + * Implementation of {@link test.nested.doc.Doc.Sec}. + */ + public static class Sec_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.doc.Doc.Sec { + /** + * Implementation of {@link test.nested.doc.Doc.Sec.Item}. + */ + public static abstract class Item_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.doc.Doc.Sec.Item { + + private test.nested.doc.Doc.Sec.Item.Kind _kind = test.nested.doc.Doc.Sec.Item.Kind.PLAIN; + + private String _package = ""; + + /** + * Creates a {@link Item_Impl} instance. + */ + public Item_Impl() { + super(); + } + + @Override + public final test.nested.doc.Doc.Sec.Item.Kind getKind() { + return _kind; + } + + @Override + public test.nested.doc.Doc.Sec.Item setKind(test.nested.doc.Doc.Sec.Item.Kind value) { + internalSetKind(value); + return this; + } + + /** Internal setter for {@link #getKind()} without chain call utility. */ + protected final void internalSetKind(test.nested.doc.Doc.Sec.Item.Kind value) { + if (value == null) throw new IllegalArgumentException("Property 'kind' cannot be null."); + _listener.beforeSet(this, KIND__PROP, value); + _kind = value; + _listener.afterChanged(this, KIND__PROP); + } + + @Override + public final String getPackage() { + return _package; + } + + @Override + public test.nested.doc.Doc.Sec.Item setPackage(String value) { + internalSetPackage(value); + return this; + } + + /** Internal setter for {@link #getPackage()} without chain call utility. */ + protected final void internalSetPackage(String value) { + _listener.beforeSet(this, PACKAGE__PROP, value); + _package = value; + _listener.afterChanged(this, PACKAGE__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.doc.Doc.Sec.Item registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.doc.Doc.Sec.Item unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + KIND__PROP, + PACKAGE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case KIND__PROP: return getKind(); + case PACKAGE__PROP: return getPackage(); + default: return test.nested.doc.Doc.Sec.Item.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case KIND__PROP: internalSetKind((test.nested.doc.Doc.Sec.Item.Kind) value); break; + case PACKAGE__PROP: internalSetPackage((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(KIND__PROP); + getKind().writeTo(out); + out.name(PACKAGE__PROP); + out.value(getPackage()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case KIND__PROP: setKind(test.nested.doc.Doc.Sec.Item.Kind.readKind(in)); break; + case PACKAGE__PROP: setPackage(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + out.name(0); + out.value(typeId()); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(KIND__ID); + getKind().writeTo(out); + out.name(PACKAGE__ID); + out.value(getPackage()); + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case KIND__ID: setKind(test.nested.doc.Doc.Sec.Item.Kind.readKind(in)); break; + case PACKAGE__ID: setPackage(in.nextString()); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc.Sec.Item} type. */ + public static final String ITEM__XML_ELEMENT = "item"; + + /** XML attribute or element name of a {@link #getKind} property. */ + private static final String KIND__XML_ATTR = "kind"; + + /** XML attribute or element name of a {@link #getPackage} property. */ + private static final String PACKAGE__XML_ATTR = "package"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(KIND__XML_ATTR, getKind().protocolName()); + out.writeAttribute(PACKAGE__XML_ATTR, getPackage()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.doc.Doc.Sec.Item} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Item_Impl readItem_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.PARA__XML_ELEMENT: { + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_XmlContent(in); + } + + case test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.CASE__XML_ELEMENT: { + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_XmlContent(in); + } + + case Figure_Impl.FIGURE__XML_ELEMENT: { + return test.nested.doc.impl.Figure_Impl.readFigure_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case KIND__XML_ATTR: { + setKind(test.nested.doc.Doc.Sec.Item.Kind.valueOfProtocol(value)); + break; + } + case PACKAGE__XML_ATTR: { + setPackage(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case KIND__XML_ATTR: { + setKind(test.nested.doc.Doc.Sec.Item.Kind.valueOfProtocol(in.getElementText())); + break; + } + case PACKAGE__XML_ATTR: { + setPackage(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + /** + * Implementation of {@link test.nested.doc.Doc.Sec.Block}. + */ + public static abstract class Block_Impl extends test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl implements test.nested.doc.Doc.Sec.Block { + + private int _weight = 0; + + /** + * Creates a {@link Block_Impl} instance. + */ + public Block_Impl() { + super(); + } + + @Override + public final int getWeight() { + return _weight; + } + + @Override + public test.nested.doc.Doc.Sec.Block setWeight(int value) { + internalSetWeight(value); + return this; + } + + /** Internal setter for {@link #getWeight()} without chain call utility. */ + protected final void internalSetWeight(int value) { + _listener.beforeSet(this, WEIGHT__PROP, value); + _weight = value; + _listener.afterChanged(this, WEIGHT__PROP); + } + + @Override + public test.nested.doc.Doc.Sec.Block setKind(test.nested.doc.Doc.Sec.Item.Kind value) { + internalSetKind(value); + return this; + } + + @Override + public test.nested.doc.Doc.Sec.Block setPackage(String value) { + internalSetPackage(value); + return this; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WEIGHT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WEIGHT__PROP: return getWeight(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WEIGHT__PROP: internalSetWeight((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WEIGHT__PROP); + out.value(getWeight()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WEIGHT__PROP: setWeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WEIGHT__ID); + out.value(getWeight()); + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case WEIGHT__ID: setWeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc.Sec.Block} type. */ + public static final String BLOCK__XML_ELEMENT = "block"; + + /** XML attribute or element name of a {@link #getWeight} property. */ + private static final String WEIGHT__XML_ATTR = "weight"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WEIGHT__XML_ATTR, Integer.toString(getWeight())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.doc.Doc.Sec.Block} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Block_Impl readBlock_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.PARA__XML_ELEMENT: { + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl.readPara_XmlContent(in); + } + + case test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.CASE__XML_ELEMENT: { + return test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl.readCase_XmlContent(in); + } + + case Figure_Impl.FIGURE__XML_ELEMENT: { + return test.nested.doc.impl.Figure_Impl.readFigure_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WEIGHT__XML_ATTR: { + setWeight(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WEIGHT__XML_ATTR: { + setWeight(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.nested.doc.Doc.Sec.Item.Visitor v, A arg) throws E { + return visit((test.nested.doc.Doc.Sec.Block.Visitor) v, arg); + } + + } + /** + * Implementation of {@link test.nested.doc.Doc.Sec.Para}. + */ + public static class Para_Impl extends test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl implements test.nested.doc.Doc.Sec.Para { + + private String _text = ""; + + /** + * Creates a {@link Para_Impl} instance. + * + * @see test.nested.doc.Doc.Sec.Para#create() + */ + public Para_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.PARA; + } + + @Override + public final String getText() { + return _text; + } + + @Override + public test.nested.doc.Doc.Sec.Para setText(String value) { + internalSetText(value); + return this; + } + + /** Internal setter for {@link #getText()} without chain call utility. */ + protected final void internalSetText(String value) { + _listener.beforeSet(this, TEXT__PROP, value); + _text = value; + _listener.afterChanged(this, TEXT__PROP); + } + + @Override + public test.nested.doc.Doc.Sec.Para setWeight(int value) { + internalSetWeight(value); + return this; + } + + @Override + public test.nested.doc.Doc.Sec.Para setKind(test.nested.doc.Doc.Sec.Item.Kind value) { + internalSetKind(value); + return this; + } + + @Override + public test.nested.doc.Doc.Sec.Para setPackage(String value) { + internalSetPackage(value); + return this; + } + + @Override + public String jsonType() { + return PARA__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TEXT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TEXT__PROP: return getText(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TEXT__PROP: internalSetText((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TEXT__PROP); + out.value(getText()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TEXT__PROP: setText(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return PARA__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TEXT__ID); + out.value(getText()); + } + + /** Helper for creating an object of type {@link test.nested.doc.Doc.Sec.Para} from a polymorphic composition. */ + public static test.nested.doc.Doc.Sec.Para readPara_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl.Para_Impl result = new Para_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case TEXT__ID: setText(in.nextString()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc.Sec.Para} type. */ + public static final String PARA__XML_ELEMENT = "para"; + + /** XML attribute or element name of a {@link #getText} property. */ + private static final String TEXT__XML_ATTR = "text"; + + @Override + public String getXmlTagName() { + return PARA__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(TEXT__XML_ATTR, getText()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.doc.Doc.Sec.Para} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Para_Impl readPara_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Para_Impl result = new Para_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case TEXT__XML_ATTR: { + setText(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TEXT__XML_ATTR: { + setText(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.doc.Doc.Sec.Block.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.doc.Doc.Sec.Case}. + */ + public static class Case_Impl extends test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl implements test.nested.doc.Doc.Sec.Case { + + private final java.util.List _children = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.beforeAdd(Case_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.afterRemove(Case_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Case_Impl.this, CHILDREN__PROP); + } + }; + + /** + * Creates a {@link Case_Impl} instance. + * + * @see test.nested.doc.Doc.Sec.Case#create() + */ + public Case_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.CASE; + } + + @Override + public final java.util.List getChildren() { + return _children; + } + + @Override + public test.nested.doc.Doc.Sec.Case setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + /** Internal setter for {@link #getChildren()} without chain call utility. */ + protected final void internalSetChildren(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'children' cannot be null."); + _children.clear(); + _children.addAll(value); + } + + @Override + public test.nested.doc.Doc.Sec.Case addChildren(test.nested.doc.Doc.Sec.Item value) { + internalAddChildren(value); + return this; + } + + /** Implementation of {@link #addChildren(test.nested.doc.Doc.Sec.Item)} without chain call utility. */ + protected final void internalAddChildren(test.nested.doc.Doc.Sec.Item value) { + _children.add(value); + } + + @Override + public final void removeChildren(test.nested.doc.Doc.Sec.Item value) { + _children.remove(value); + } + + @Override + public test.nested.doc.Doc.Sec.Case setWeight(int value) { + internalSetWeight(value); + return this; + } + + @Override + public test.nested.doc.Doc.Sec.Case setKind(test.nested.doc.Doc.Sec.Item.Kind value) { + internalSetKind(value); + return this; + } + + @Override + public test.nested.doc.Doc.Sec.Case setPackage(String value) { + internalSetPackage(value); + return this; + } + + @Override + public String jsonType() { + return CASE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + CHILDREN__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case CHILDREN__PROP: return getChildren(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case CHILDREN__PROP: internalSetChildren(de.haumacher.msgbuf.util.Conversions.asList(test.nested.doc.Doc.Sec.Item.class, value)); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(CHILDREN__PROP); + out.beginArray(); + for (test.nested.doc.Doc.Sec.Item x : getChildren()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case CHILDREN__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + setChildren(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return CASE__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(CHILDREN__ID); + { + java.util.List values = getChildren(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.doc.Doc.Sec.Item x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.doc.Doc.Sec.Case} from a polymorphic composition. */ + public static test.nested.doc.Doc.Sec.Case readCase_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl.Case_Impl result = new Case_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case CHILDREN__ID: { + in.beginArray(); + while (in.hasNext()) { + addChildren(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc.Sec.Case} type. */ + public static final String CASE__XML_ELEMENT = "case"; + + /** XML attribute or element name of a {@link #getChildren} property. */ + private static final String CHILDREN__XML_ATTR = "children"; + + @Override + public String getXmlTagName() { + return CASE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + out.writeStartElement(CHILDREN__XML_ATTR); + for (test.nested.doc.Doc.Sec.Item element : getChildren()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.doc.Doc.Sec.Case} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Case_Impl readCase_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Case_Impl result = new Case_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case CHILDREN__XML_ATTR: { + internalReadChildrenListXml(in); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + private void internalReadChildrenListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addChildren(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in)); + } + } + + @Override + public R visit(test.nested.doc.Doc.Sec.Block.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + /** + * Creates a {@link Sec_Impl} instance. + * + * @see test.nested.doc.Doc.Sec#create() + */ + public Sec_Impl() { + super(); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.doc.Doc.Sec registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.doc.Doc.Sec unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return SEC__TYPE; + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + // No fields to write, hook for subclasses. + } + + /** Helper for creating an object of type {@link test.nested.doc.Doc.Sec} from a polymorphic composition. */ + public static test.nested.doc.Doc.Sec readSec_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl.Sec_Impl result = new Sec_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc.Sec} type. */ + public static final String SEC__XML_ELEMENT = "sec"; + + @Override + public String getXmlTagName() { + return SEC__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.doc.Doc.Sec} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sec_Impl readSec_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Sec_Impl result = new Sec_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + + private final java.util.List _items = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.beforeAdd(Doc_Impl.this, ITEMS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.afterRemove(Doc_Impl.this, ITEMS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Doc_Impl.this, ITEMS__PROP); + } + }; + + private final java.util.Map _byName = new de.haumacher.msgbuf.util.ReferenceMap() { + @Override + protected void beforeAdd(String index, test.nested.doc.Doc.Sec.Item element) { + _listener.beforeAdd(Doc_Impl.this, BY_NAME__PROP, index, element); + } + + @Override + protected void afterRemove(String index, test.nested.doc.Doc.Sec.Item element) { + _listener.afterRemove(Doc_Impl.this, BY_NAME__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Doc_Impl.this, BY_NAME__PROP); + } + }; + + private test.nested.doc.Doc.Sec.Item _maybe = null; + + /** + * Creates a {@link Doc_Impl} instance. + * + * @see test.nested.doc.Doc#create() + */ + public Doc_Impl() { + super(); + } + + @Override + public final java.util.List getItems() { + return _items; + } + + @Override + public test.nested.doc.Doc setItems(java.util.List value) { + internalSetItems(value); + return this; + } + + /** Internal setter for {@link #getItems()} without chain call utility. */ + protected final void internalSetItems(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'items' cannot be null."); + _items.clear(); + _items.addAll(value); + } + + @Override + public test.nested.doc.Doc addItem(test.nested.doc.Doc.Sec.Item value) { + internalAddItem(value); + return this; + } + + /** Implementation of {@link #addItem(test.nested.doc.Doc.Sec.Item)} without chain call utility. */ + protected final void internalAddItem(test.nested.doc.Doc.Sec.Item value) { + _items.add(value); + } + + @Override + public final void removeItem(test.nested.doc.Doc.Sec.Item value) { + _items.remove(value); + } + + @Override + public final java.util.Map getByName() { + return _byName; + } + + @Override + public test.nested.doc.Doc setByName(java.util.Map value) { + internalSetByName(value); + return this; + } + + /** Internal setter for {@link #getByName()} without chain call utility. */ + protected final void internalSetByName(java.util.Map value) { + if (value == null) throw new IllegalArgumentException("Property 'byName' cannot be null."); + _byName.clear(); + _byName.putAll(value); + } + + @Override + public test.nested.doc.Doc putByName(String key, test.nested.doc.Doc.Sec.Item value) { + internalPutByName(key, value); + return this; + } + + /** Implementation of {@link #putByName(String, test.nested.doc.Doc.Sec.Item)} without chain call utility. */ + protected final void internalPutByName(String key, test.nested.doc.Doc.Sec.Item value) { + if (_byName.containsKey(key)) { + throw new IllegalArgumentException("Property 'byName' already contains a value for key '" + key + "'."); + } + _byName.put(key, value); + } + + @Override + public final void removeByName(String key) { + _byName.remove(key); + } + + @Override + public final test.nested.doc.Doc.Sec.Item getMaybe() { + return _maybe; + } + + @Override + public test.nested.doc.Doc setMaybe(test.nested.doc.Doc.Sec.Item value) { + internalSetMaybe(value); + return this; + } + + /** Internal setter for {@link #getMaybe()} without chain call utility. */ + protected final void internalSetMaybe(test.nested.doc.Doc.Sec.Item value) { + _listener.beforeSet(this, MAYBE__PROP, value); + _maybe = value; + _listener.afterChanged(this, MAYBE__PROP); + } + + @Override + public final boolean hasMaybe() { + return _maybe != null; + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.doc.Doc registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.doc.Doc unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return DOC__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + ITEMS__PROP, + BY_NAME__PROP, + MAYBE__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case ITEMS__PROP: return getItems(); + case BY_NAME__PROP: return getByName(); + case MAYBE__PROP: return getMaybe(); + default: return test.nested.doc.Doc.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case ITEMS__PROP: internalSetItems(de.haumacher.msgbuf.util.Conversions.asList(test.nested.doc.Doc.Sec.Item.class, value)); break; + case BY_NAME__PROP: internalSetByName((java.util.Map) value); break; + case MAYBE__PROP: internalSetMaybe((test.nested.doc.Doc.Sec.Item) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(ITEMS__PROP); + out.beginArray(); + for (test.nested.doc.Doc.Sec.Item x : getItems()) { + x.writeTo(out); + } + out.endArray(); + out.name(BY_NAME__PROP); + out.beginObject(); + for (java.util.Map.Entry entry : getByName().entrySet()) { + out.name(entry.getKey()); + entry.getValue().writeTo(out); + } + out.endObject(); + if (hasMaybe()) { + out.name(MAYBE__PROP); + getMaybe().writeTo(out); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case ITEMS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + setItems(newValue); + } + break; + case BY_NAME__PROP: { + java.util.Map newValue = new java.util.LinkedHashMap<>(); + in.beginObject(); + while (in.hasNext()) { + newValue.put(in.nextName(), test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endObject(); + setByName(newValue); + break; + } + case MAYBE__PROP: setMaybe(test.nested.doc.Doc.Sec.Item.readItem(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(ITEMS__ID); + { + java.util.List values = getItems(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.doc.Doc.Sec.Item x : values) { + x.writeTo(out); + } + out.endArray(); + } + out.name(BY_NAME__ID); + { + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, getByName().size()); + for (java.util.Map.Entry entry : getByName().entrySet()) { + out.beginObject(); + out.name(1); + out.value(entry.getKey()); + out.name(2); + entry.getValue().writeTo(out); + out.endObject(); + } + out.endArray(); + } + if (hasMaybe()) { + out.name(MAYBE__ID); + getMaybe().writeTo(out); + } + } + + /** Helper for creating an object of type {@link test.nested.doc.Doc} from a polymorphic composition. */ + public static test.nested.doc.Doc readDoc_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.doc.impl.Doc_Impl result = new Doc_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case ITEMS__ID: { + in.beginArray(); + while (in.hasNext()) { + addItem(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + } + break; + case BY_NAME__ID: { + in.beginArray(); + while (in.hasNext()) { + in.beginObject(); + String key = ""; + test.nested.doc.Doc.Sec.Item value = null; + while (in.hasNext()) { + switch (in.nextName()) { + case 1: key = in.nextString(); break; + case 2: value = test.nested.doc.Doc.Sec.Item.readItem(in); break; + default: in.skipValue(); break; + } + } + putByName(key, value); + in.endObject(); + } + in.endArray(); + break; + } + case MAYBE__ID: setMaybe(test.nested.doc.Doc.Sec.Item.readItem(in)); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.doc.Doc} type. */ + public static final String DOC__XML_ELEMENT = "doc"; + + /** XML attribute or element name of a {@link #getItems} property. */ + private static final String ITEMS__XML_ATTR = "items"; + + /** XML attribute or element name of a {@link #getByName} property. */ + private static final String BY_NAME__XML_ATTR = "by-name"; + + /** XML attribute or element name of a {@link #getMaybe} property. */ + private static final String MAYBE__XML_ATTR = "maybe"; + + @Override + public String getXmlTagName() { + return DOC__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeStartElement(ITEMS__XML_ATTR); + for (test.nested.doc.Doc.Sec.Item element : getItems()) { + element.writeTo(out); + } + out.writeEndElement(); + if (hasMaybe()) { + out.writeStartElement(MAYBE__XML_ATTR); + getMaybe().writeTo(out); + out.writeEndElement(); + } + } + + /** Creates a new {@link test.nested.doc.Doc} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Doc_Impl readDoc_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Doc_Impl result = new Doc_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case ITEMS__XML_ATTR: { + internalReadItemsListXml(in); + break; + } + case MAYBE__XML_ATTR: { + in.nextTag(); + setMaybe(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadItemsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addItem(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Figure_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Figure_Impl.java new file mode 100644 index 00000000..b790f83e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/doc/impl/Figure_Impl.java @@ -0,0 +1,217 @@ +package test.nested.doc.impl; + +/** + * Implementation of {@link test.nested.doc.Figure}. + */ +public class Figure_Impl extends test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl implements test.nested.doc.Figure { + + private String _src = ""; + + /** + * Creates a {@link Figure_Impl} instance. + * + * @see test.nested.doc.Figure#create() + */ + public Figure_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.FIGURE; + } + + @Override + public final String getSrc() { + return _src; + } + + @Override + public test.nested.doc.Figure setSrc(String value) { + internalSetSrc(value); + return this; + } + + /** Internal setter for {@link #getSrc()} without chain call utility. */ + protected final void internalSetSrc(String value) { + _listener.beforeSet(this, SRC__PROP, value); + _src = value; + _listener.afterChanged(this, SRC__PROP); + } + + @Override + public test.nested.doc.Figure setWeight(int value) { + internalSetWeight(value); + return this; + } + + @Override + public test.nested.doc.Figure setKind(test.nested.doc.Doc.Sec.Item.Kind value) { + internalSetKind(value); + return this; + } + + @Override + public test.nested.doc.Figure setPackage(String value) { + internalSetPackage(value); + return this; + } + + @Override + public String jsonType() { + return FIGURE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SRC__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.doc.impl.Doc_Impl.Sec_Impl.Block_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SRC__PROP: return getSrc(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SRC__PROP: internalSetSrc((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SRC__PROP); + out.value(getSrc()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SRC__PROP: setSrc(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return FIGURE__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SRC__ID); + out.value(getSrc()); + } + + /** Helper for creating an object of type {@link test.nested.doc.Figure} from a polymorphic composition. */ + public static test.nested.doc.Figure readFigure_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.doc.impl.Figure_Impl result = new Figure_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case SRC__ID: setSrc(in.nextString()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.doc.Figure} type. */ + public static final String FIGURE__XML_ELEMENT = "figure"; + + /** XML attribute or element name of a {@link #getSrc} property. */ + private static final String SRC__XML_ATTR = "src"; + + @Override + public String getXmlTagName() { + return FIGURE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(SRC__XML_ATTR, getSrc()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.doc.Figure} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Figure_Impl readFigure_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Figure_Impl result = new Figure_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case SRC__XML_ATTR: { + setSrc(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SRC__XML_ATTR: { + setSrc(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.doc.Doc.Sec.Block.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/Note.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/Note.java new file mode 100644 index 00000000..45619068 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/Note.java @@ -0,0 +1,144 @@ +package test.nested.note; + +/** + * References to a nested polymorphic hierarchy of another file (issue #16). + */ +public interface Note extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Inner extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.nested.note.Note.Inner} instance. + */ + static test.nested.note.Note.Inner create() { + return new test.nested.note.impl.Note_Impl.Inner_Impl(); + } + + /** Identifier for the {@link test.nested.note.Note.Inner} type in JSON format. */ + String INNER__TYPE = "Inner"; + + /** @see #getRefs() */ + String REFS__PROP = "refs"; + + /** Identifier for the property {@link #getRefs()} in binary format. */ + static final int REFS__ID = 1; + + java.util.List getRefs(); + + /** + * @see #getRefs() + */ + test.nested.note.Note.Inner setRefs(java.util.List value); + + /** + * Adds a value to the {@link #getRefs()} list. + */ + test.nested.note.Note.Inner addRef(test.nested.doc.Doc.Sec.Item value); + + /** + * Removes a value from the {@link #getRefs()} list. + */ + void removeRef(test.nested.doc.Doc.Sec.Item value); + + @Override + public test.nested.note.Note.Inner registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.note.Note.Inner unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.note.Note.Inner readInner(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.note.impl.Note_Impl.Inner_Impl result = new test.nested.note.impl.Note_Impl.Inner_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.note.Note.Inner readInner(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.note.Note.Inner result = test.nested.note.impl.Note_Impl.Inner_Impl.readInner_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Inner} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Inner readInner(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.note.impl.Note_Impl.Inner_Impl.readInner_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.note.Note} instance. + */ + static test.nested.note.Note create() { + return new test.nested.note.impl.Note_Impl(); + } + + /** Identifier for the {@link test.nested.note.Note} type in JSON format. */ + String NOTE__TYPE = "Note"; + + /** @see #getTarget() */ + String TARGET__PROP = "target"; + + /** @see #getInner() */ + String INNER__PROP = "inner"; + + /** Identifier for the property {@link #getTarget()} in binary format. */ + static final int TARGET__ID = 1; + + /** Identifier for the property {@link #getInner()} in binary format. */ + static final int INNER__ID = 2; + + test.nested.doc.Doc.Sec.Item getTarget(); + + /** + * @see #getTarget() + */ + test.nested.note.Note setTarget(test.nested.doc.Doc.Sec.Item value); + + /** + * Checks, whether {@link #getTarget()} has a value. + */ + boolean hasTarget(); + + test.nested.note.Note.Inner getInner(); + + /** + * @see #getInner() + */ + test.nested.note.Note setInner(test.nested.note.Note.Inner value); + + /** + * Checks, whether {@link #getInner()} has a value. + */ + boolean hasInner(); + + @Override + public test.nested.note.Note registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.note.Note unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.note.Note readNote(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.note.impl.Note_Impl result = new test.nested.note.impl.Note_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.note.Note readNote(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.note.Note result = test.nested.note.impl.Note_Impl.readNote_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Note} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Note readNote(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.note.impl.Note_Impl.readNote_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/impl/Note_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/impl/Note_Impl.java new file mode 100644 index 00000000..5a63ebbe --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/impl/Note_Impl.java @@ -0,0 +1,638 @@ +package test.nested.note.impl; + +/** + * Implementation of {@link test.nested.note.Note}. + */ +public class Note_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.note.Note { + /** + * Implementation of {@link test.nested.note.Note.Inner}. + */ + public static class Inner_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.note.Note.Inner { + + private final java.util.List _refs = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.beforeAdd(Inner_Impl.this, REFS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.doc.Doc.Sec.Item element) { + _listener.afterRemove(Inner_Impl.this, REFS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Inner_Impl.this, REFS__PROP); + } + }; + + /** + * Creates a {@link Inner_Impl} instance. + * + * @see test.nested.note.Note.Inner#create() + */ + public Inner_Impl() { + super(); + } + + @Override + public final java.util.List getRefs() { + return _refs; + } + + @Override + public test.nested.note.Note.Inner setRefs(java.util.List value) { + internalSetRefs(value); + return this; + } + + /** Internal setter for {@link #getRefs()} without chain call utility. */ + protected final void internalSetRefs(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'refs' cannot be null."); + _refs.clear(); + _refs.addAll(value); + } + + @Override + public test.nested.note.Note.Inner addRef(test.nested.doc.Doc.Sec.Item value) { + internalAddRef(value); + return this; + } + + /** Implementation of {@link #addRef(test.nested.doc.Doc.Sec.Item)} without chain call utility. */ + protected final void internalAddRef(test.nested.doc.Doc.Sec.Item value) { + _refs.add(value); + } + + @Override + public final void removeRef(test.nested.doc.Doc.Sec.Item value) { + _refs.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.note.Note.Inner registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.note.Note.Inner unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return INNER__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + REFS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case REFS__PROP: return getRefs(); + default: return test.nested.note.Note.Inner.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case REFS__PROP: internalSetRefs(de.haumacher.msgbuf.util.Conversions.asList(test.nested.doc.Doc.Sec.Item.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(REFS__PROP); + out.beginArray(); + for (test.nested.doc.Doc.Sec.Item x : getRefs()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case REFS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + setRefs(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(REFS__ID); + { + java.util.List values = getRefs(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.doc.Doc.Sec.Item x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.note.Note.Inner} from a polymorphic composition. */ + public static test.nested.note.Note.Inner readInner_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.note.impl.Note_Impl.Inner_Impl result = new Inner_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case REFS__ID: { + in.beginArray(); + while (in.hasNext()) { + addRef(test.nested.doc.Doc.Sec.Item.readItem(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.note.Note.Inner} type. */ + public static final String INNER__XML_ELEMENT = "inner"; + + /** XML attribute or element name of a {@link #getRefs} property. */ + private static final String REFS__XML_ATTR = "refs"; + + @Override + public String getXmlTagName() { + return INNER__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeStartElement(REFS__XML_ATTR); + for (test.nested.doc.Doc.Sec.Item element : getRefs()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.note.Note.Inner} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Inner_Impl readInner_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Inner_Impl result = new Inner_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case REFS__XML_ATTR: { + internalReadRefsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadRefsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addRef(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in)); + } + } + + } + + private test.nested.doc.Doc.Sec.Item _target = null; + + private test.nested.note.Note.Inner _inner = null; + + /** + * Creates a {@link Note_Impl} instance. + * + * @see test.nested.note.Note#create() + */ + public Note_Impl() { + super(); + } + + @Override + public final test.nested.doc.Doc.Sec.Item getTarget() { + return _target; + } + + @Override + public test.nested.note.Note setTarget(test.nested.doc.Doc.Sec.Item value) { + internalSetTarget(value); + return this; + } + + /** Internal setter for {@link #getTarget()} without chain call utility. */ + protected final void internalSetTarget(test.nested.doc.Doc.Sec.Item value) { + _listener.beforeSet(this, TARGET__PROP, value); + _target = value; + _listener.afterChanged(this, TARGET__PROP); + } + + @Override + public final boolean hasTarget() { + return _target != null; + } + + @Override + public final test.nested.note.Note.Inner getInner() { + return _inner; + } + + @Override + public test.nested.note.Note setInner(test.nested.note.Note.Inner value) { + internalSetInner(value); + return this; + } + + /** Internal setter for {@link #getInner()} without chain call utility. */ + protected final void internalSetInner(test.nested.note.Note.Inner value) { + _listener.beforeSet(this, INNER__PROP, value); + _inner = value; + _listener.afterChanged(this, INNER__PROP); + } + + @Override + public final boolean hasInner() { + return _inner != null; + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.note.Note registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.note.Note unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return NOTE__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TARGET__PROP, + INNER__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TARGET__PROP: return getTarget(); + case INNER__PROP: return getInner(); + default: return test.nested.note.Note.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TARGET__PROP: internalSetTarget((test.nested.doc.Doc.Sec.Item) value); break; + case INNER__PROP: internalSetInner((test.nested.note.Note.Inner) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasTarget()) { + out.name(TARGET__PROP); + getTarget().writeTo(out); + } + if (hasInner()) { + out.name(INNER__PROP); + getInner().writeTo(out); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TARGET__PROP: setTarget(test.nested.doc.Doc.Sec.Item.readItem(in)); break; + case INNER__PROP: setInner(test.nested.note.Note.Inner.readInner(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasTarget()) { + out.name(TARGET__ID); + getTarget().writeTo(out); + } + if (hasInner()) { + out.name(INNER__ID); + getInner().writeTo(out); + } + } + + /** Helper for creating an object of type {@link test.nested.note.Note} from a polymorphic composition. */ + public static test.nested.note.Note readNote_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.note.impl.Note_Impl result = new Note_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case TARGET__ID: setTarget(test.nested.doc.Doc.Sec.Item.readItem(in)); break; + case INNER__ID: setInner(test.nested.note.Note.Inner.readInner(in)); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.note.Note} type. */ + public static final String NOTE__XML_ELEMENT = "note"; + + /** XML attribute or element name of a {@link #getTarget} property. */ + private static final String TARGET__XML_ATTR = "target"; + + /** XML attribute or element name of a {@link #getInner} property. */ + private static final String INNER__XML_ATTR = "inner"; + + @Override + public String getXmlTagName() { + return NOTE__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasTarget()) { + out.writeStartElement(TARGET__XML_ATTR); + getTarget().writeTo(out); + out.writeEndElement(); + } + if (hasInner()) { + out.writeStartElement(INNER__XML_ATTR); + getInner().writeContent(out); + out.writeEndElement(); + } + } + + /** Creates a new {@link test.nested.note.Note} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Note_Impl readNote_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Note_Impl result = new Note_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TARGET__XML_ATTR: { + in.nextTag(); + setTarget(test.nested.doc.impl.Doc_Impl.Sec_Impl.Item_Impl.readItem_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case INNER__XML_ATTR: { + setInner(test.nested.note.impl.Note_Impl.Inner_Impl.readInner_XmlContent(in)); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/note.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/note.proto new file mode 100644 index 00000000..c576a8e4 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/note/note.proto @@ -0,0 +1,13 @@ +package test.nested.note; +import "../doc/doc.proto"; + +/** + * References to a nested polymorphic hierarchy of another file (issue #16). + */ +message Note { + message Inner { + repeated test.nested.doc.Doc.Sec.Item refs; + } + test.nested.doc.Doc.Sec.Item target; + Inner inner; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java new file mode 100644 index 00000000..84f9f31d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java @@ -0,0 +1,182 @@ +package test.nested.owbase; + +/** + * An OpenWorld hierarchy with a nested abstract root (issue #16). + */ +public interface Events extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + /** + * Nested abstract root, extended from another file. + */ + public interface Event extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.owbase.Events.Event} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.owbase.Events.TextEvent}. */ + TEXT_EVENT, + ; + + } + + /** Registry for dynamically registered subtypes. */ + static final java.util.Map> REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for polymorphic deserialization. + */ + static void register(String typeId, de.haumacher.msgbuf.data.Factory factory) { + REGISTRY.put(typeId, factory); + } + + /** Visitor interface for the {@link test.nested.owbase.Events.Event} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.owbase.Events.TextEvent}.*/ + R visit(test.nested.owbase.Events.TextEvent self, A arg) throws E; + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.nested.owbase.Events.Event self, A arg) throws E; + + } + + /** @see #getTimestamp() */ + String TIMESTAMP__PROP = "timestamp"; + + /** The type code of this instance. */ + TypeKind kind(); + + long getTimestamp(); + + /** + * @see #getTimestamp() + */ + test.nested.owbase.Events.Event setTimestamp(long value); + + @Override + public test.nested.owbase.Events.Event registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.owbase.Events.Event unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.owbase.Events.Event readEvent(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owbase.Events.Event result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.owbase.Events.TextEvent.TEXT_EVENT__TYPE: result = test.nested.owbase.Events.TextEvent.readTextEvent(in); break; + default: { + de.haumacher.msgbuf.data.Factory factory = test.nested.owbase.Events.Event.REGISTRY.get(type); + if (factory != null) { + result = factory.create(); + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Creates a new {@link Event} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Event readEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owbase.impl.Events_Impl.Event_Impl.readEvent_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface TextEvent extends test.nested.owbase.Events.Event { + + /** + * Creates a {@link test.nested.owbase.Events.TextEvent} instance. + */ + static test.nested.owbase.Events.TextEvent create() { + return new test.nested.owbase.impl.Events_Impl.TextEvent_Impl(); + } + + /** Identifier for the {@link test.nested.owbase.Events.TextEvent} type in JSON format. */ + String TEXT_EVENT__TYPE = "TextEvent"; + + /** @see #getText() */ + String TEXT__PROP = "text"; + + String getText(); + + /** + * @see #getText() + */ + test.nested.owbase.Events.TextEvent setText(String value); + + @Override + test.nested.owbase.Events.TextEvent setTimestamp(long value); + + /** Reads a new instance from the given reader. */ + static test.nested.owbase.Events.TextEvent readTextEvent(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owbase.impl.Events_Impl.TextEvent_Impl result = new test.nested.owbase.impl.Events_Impl.TextEvent_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link TextEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static TextEvent readTextEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owbase.impl.Events_Impl.TextEvent_Impl.readTextEvent_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.owbase.Events} instance. + */ + static test.nested.owbase.Events create() { + return new test.nested.owbase.impl.Events_Impl(); + } + + /** Identifier for the {@link test.nested.owbase.Events} type in JSON format. */ + String EVENTS__TYPE = "Events"; + + /** @see #getEvents() */ + String EVENTS__PROP = "events"; + + java.util.List getEvents(); + + /** + * @see #getEvents() + */ + test.nested.owbase.Events setEvents(java.util.List value); + + /** + * Adds a value to the {@link #getEvents()} list. + */ + test.nested.owbase.Events addEvent(test.nested.owbase.Events.Event value); + + /** + * Removes a value from the {@link #getEvents()} list. + */ + void removeEvent(test.nested.owbase.Events.Event value); + + @Override + public test.nested.owbase.Events registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.owbase.Events unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.owbase.Events readEvents(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owbase.impl.Events_Impl result = new test.nested.owbase.impl.Events_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Events} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Events readEvents(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owbase.impl.Events_Impl.readEvents_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java new file mode 100644 index 00000000..547e6ed4 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java @@ -0,0 +1,658 @@ +package test.nested.owbase.impl; + +/** + * Implementation of {@link test.nested.owbase.Events}. + */ +public class Events_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.owbase.Events { + /** + * Implementation of {@link test.nested.owbase.Events.Event}. + */ + public static abstract class Event_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.owbase.Events.Event { + + static { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + } + + private long _timestamp = 0L; + + /** + * Creates a {@link Event_Impl} instance. + */ + public Event_Impl() { + super(); + } + + @Override + public final long getTimestamp() { + return _timestamp; + } + + @Override + public test.nested.owbase.Events.Event setTimestamp(long value) { + internalSetTimestamp(value); + return this; + } + + /** Internal setter for {@link #getTimestamp()} without chain call utility. */ + protected final void internalSetTimestamp(long value) { + _listener.beforeSet(this, TIMESTAMP__PROP, value); + _timestamp = value; + _listener.afterChanged(this, TIMESTAMP__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.owbase.Events.Event registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.owbase.Events.Event unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TIMESTAMP__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TIMESTAMP__PROP: return getTimestamp(); + default: return test.nested.owbase.Events.Event.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TIMESTAMP__PROP: internalSetTimestamp((long) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TIMESTAMP__PROP); + out.value(getTimestamp()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TIMESTAMP__PROP: setTimestamp(in.nextLong()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.owbase.Events.Event} type. */ + public static final String EVENT__XML_ELEMENT = "event"; + + /** XML attribute or element name of a {@link #getTimestamp} property. */ + private static final String TIMESTAMP__XML_ATTR = "timestamp"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(TIMESTAMP__XML_ATTR, Long.toString(getTimestamp())); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.owbase.Events.Event} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Event_Impl readEvent_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.owbase.impl.Events_Impl.TextEvent_Impl.TEXT_EVENT__XML_ELEMENT: { + return test.nested.owbase.impl.Events_Impl.TextEvent_Impl.readTextEvent_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case TIMESTAMP__XML_ATTR: { + setTimestamp(Long.parseLong(value)); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TIMESTAMP__XML_ATTR: { + setTimestamp(Long.parseLong(in.getElementText())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + /** + * Implementation of {@link test.nested.owbase.Events.TextEvent}. + */ + public static class TextEvent_Impl extends test.nested.owbase.impl.Events_Impl.Event_Impl implements test.nested.owbase.Events.TextEvent { + + private String _text = ""; + + /** + * Creates a {@link TextEvent_Impl} instance. + * + * @see test.nested.owbase.Events.TextEvent#create() + */ + public TextEvent_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.TEXT_EVENT; + } + + @Override + public final String getText() { + return _text; + } + + @Override + public test.nested.owbase.Events.TextEvent setText(String value) { + internalSetText(value); + return this; + } + + /** Internal setter for {@link #getText()} without chain call utility. */ + protected final void internalSetText(String value) { + _listener.beforeSet(this, TEXT__PROP, value); + _text = value; + _listener.afterChanged(this, TEXT__PROP); + } + + @Override + public test.nested.owbase.Events.TextEvent setTimestamp(long value) { + internalSetTimestamp(value); + return this; + } + + @Override + public String jsonType() { + return TEXT_EVENT__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TEXT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TEXT__PROP: return getText(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TEXT__PROP: internalSetText((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TEXT__PROP); + out.value(getText()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TEXT__PROP: setText(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.owbase.Events.TextEvent} type. */ + public static final String TEXT_EVENT__XML_ELEMENT = "text-event"; + + /** XML attribute or element name of a {@link #getText} property. */ + private static final String TEXT__XML_ATTR = "text"; + + @Override + public String getXmlTagName() { + return TEXT_EVENT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(TEXT__XML_ATTR, getText()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.owbase.Events.TextEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static TextEvent_Impl readTextEvent_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + TextEvent_Impl result = new TextEvent_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case TEXT__XML_ATTR: { + setText(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TEXT__XML_ATTR: { + setText(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.owbase.Events.Event.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + private final java.util.List _events = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.owbase.Events.Event element) { + _listener.beforeAdd(Events_Impl.this, EVENTS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.owbase.Events.Event element) { + _listener.afterRemove(Events_Impl.this, EVENTS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Events_Impl.this, EVENTS__PROP); + } + }; + + /** + * Creates a {@link Events_Impl} instance. + * + * @see test.nested.owbase.Events#create() + */ + public Events_Impl() { + super(); + } + + @Override + public final java.util.List getEvents() { + return _events; + } + + @Override + public test.nested.owbase.Events setEvents(java.util.List value) { + internalSetEvents(value); + return this; + } + + /** Internal setter for {@link #getEvents()} without chain call utility. */ + protected final void internalSetEvents(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'events' cannot be null."); + _events.clear(); + _events.addAll(value); + } + + @Override + public test.nested.owbase.Events addEvent(test.nested.owbase.Events.Event value) { + internalAddEvent(value); + return this; + } + + /** Implementation of {@link #addEvent(test.nested.owbase.Events.Event)} without chain call utility. */ + protected final void internalAddEvent(test.nested.owbase.Events.Event value) { + _events.add(value); + } + + @Override + public final void removeEvent(test.nested.owbase.Events.Event value) { + _events.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.owbase.Events registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.owbase.Events unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return EVENTS__TYPE; + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + EVENTS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case EVENTS__PROP: return getEvents(); + default: return test.nested.owbase.Events.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case EVENTS__PROP: internalSetEvents(de.haumacher.msgbuf.util.Conversions.asList(test.nested.owbase.Events.Event.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(EVENTS__PROP); + out.beginArray(); + for (test.nested.owbase.Events.Event x : getEvents()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case EVENTS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.owbase.Events.Event.readEvent(in)); + } + in.endArray(); + setEvents(newValue); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.owbase.Events} type. */ + public static final String EVENTS__XML_ELEMENT = "events"; + + /** XML attribute or element name of a {@link #getEvents} property. */ + private static final String EVENTS__XML_ATTR = "events"; + + @Override + public String getXmlTagName() { + return EVENTS__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeStartElement(EVENTS__XML_ATTR); + for (test.nested.owbase.Events.Event element : getEvents()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.owbase.Events} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Events_Impl readEvents_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Events_Impl result = new Events_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case EVENTS__XML_ATTR: { + internalReadEventsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadEventsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addEvent(test.nested.owbase.impl.Events_Impl.Event_Impl.readEvent_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/owbase.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/owbase.proto new file mode 100644 index 00000000..369a7ddd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/owbase.proto @@ -0,0 +1,19 @@ +package test.nested.owbase; + +option OpenWorld; + +/** + * An OpenWorld hierarchy with a nested abstract root (issue #16). + */ +message Events { + /** Nested abstract root, extended from another file. */ + abstract message Event { + long timestamp; + } + + message TextEvent extends Event { + string text; + } + + repeated Event events; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/CountEvent.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/CountEvent.java new file mode 100644 index 00000000..2761922d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/CountEvent.java @@ -0,0 +1,52 @@ +package test.nested.owcount; + +/** + * A top-level extension of a nested OpenWorld root declared in another file. + */ +public interface CountEvent extends test.nested.owbase.Events.Event { + + /** Extended visitor that can handle {@link CountEvent}. */ + public interface Visitor extends test.nested.owbase.Events.Event.Visitor { + + /** Visit case for {@link CountEvent}. */ + R visit(test.nested.owcount.CountEvent self, A arg) throws E; + + } + + /** + * Creates a {@link test.nested.owcount.CountEvent} instance. + */ + static test.nested.owcount.CountEvent create() { + return new test.nested.owcount.impl.CountEvent_Impl(); + } + + /** Identifier for the {@link test.nested.owcount.CountEvent} type in JSON format. */ + String COUNT_EVENT__TYPE = "CountEvent"; + + /** @see #getCount() */ + String COUNT__PROP = "count"; + + int getCount(); + + /** + * @see #getCount() + */ + test.nested.owcount.CountEvent setCount(int value); + + @Override + test.nested.owcount.CountEvent setTimestamp(long value); + + /** Reads a new instance from the given reader. */ + static test.nested.owcount.CountEvent readCountEvent(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owcount.impl.CountEvent_Impl result = new test.nested.owcount.impl.CountEvent_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link CountEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static CountEvent readCountEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owcount.impl.CountEvent_Impl.readCountEvent_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java new file mode 100644 index 00000000..ac890314 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java @@ -0,0 +1,19 @@ +package test.nested.owcount; + +/** + * Registration of extension types for the OpenWorld protocol. + */ +public class OwcountTypes implements de.haumacher.msgbuf.data.TypeRegistration { + + @Override + public void register() { + test.nested.owbase.Events.Event.register(test.nested.owcount.CountEvent.COUNT_EVENT__TYPE, test.nested.owcount.CountEvent::create); + } + + /** + * Explicit initialization for GWT or manual use. + */ + public static void init() { + new OwcountTypes().register(); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/impl/CountEvent_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/impl/CountEvent_Impl.java new file mode 100644 index 00000000..c7147658 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/impl/CountEvent_Impl.java @@ -0,0 +1,181 @@ +package test.nested.owcount.impl; + +/** + * Implementation of {@link test.nested.owcount.CountEvent}. + */ +public class CountEvent_Impl extends test.nested.owbase.impl.Events_Impl.Event_Impl implements test.nested.owcount.CountEvent { + + private int _count = 0; + + /** + * Creates a {@link CountEvent_Impl} instance. + * + * @see test.nested.owcount.CountEvent#create() + */ + public CountEvent_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final int getCount() { + return _count; + } + + @Override + public test.nested.owcount.CountEvent setCount(int value) { + internalSetCount(value); + return this; + } + + /** Internal setter for {@link #getCount()} without chain call utility. */ + protected final void internalSetCount(int value) { + _listener.beforeSet(this, COUNT__PROP, value); + _count = value; + _listener.afterChanged(this, COUNT__PROP); + } + + @Override + public test.nested.owcount.CountEvent setTimestamp(long value) { + internalSetTimestamp(value); + return this; + } + + @Override + public String jsonType() { + return COUNT_EVENT__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + COUNT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case COUNT__PROP: return getCount(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case COUNT__PROP: internalSetCount((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(COUNT__PROP); + out.value(getCount()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case COUNT__PROP: setCount(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.owcount.CountEvent} type. */ + public static final String COUNT_EVENT__XML_ELEMENT = "count-event"; + + /** XML attribute or element name of a {@link #getCount} property. */ + private static final String COUNT__XML_ATTR = "count"; + + @Override + public String getXmlTagName() { + return COUNT_EVENT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(COUNT__XML_ATTR, Integer.toString(getCount())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.owcount.CountEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static CountEvent_Impl readCountEvent_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + CountEvent_Impl result = new CountEvent_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case COUNT__XML_ATTR: { + setCount(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case COUNT__XML_ATTR: { + setCount(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.owbase.Events.Event.Visitor v, A arg) throws E { + if (v instanceof test.nested.owcount.CountEvent.Visitor) { + return ((test.nested.owcount.CountEvent.Visitor) v).visit(this, arg); + } + return v.visitDefault(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/owcount.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/owcount.proto new file mode 100644 index 00000000..f788d511 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/owcount.proto @@ -0,0 +1,8 @@ +package test.nested.owcount; + +import "../owbase/owbase.proto"; + +/** A top-level extension of a nested OpenWorld root declared in another file. */ +message CountEvent extends test.nested.owbase.Events.Event { + int32 count; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java new file mode 100644 index 00000000..e792e17e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java @@ -0,0 +1,19 @@ +package test.nested.owext; + +/** + * Registration of extension types for the OpenWorld protocol. + */ +public class OwextTypes implements de.haumacher.msgbuf.data.TypeRegistration { + + @Override + public void register() { + test.nested.owbase.Events.Event.register(test.nested.owext.Patches.PatchEvent.PATCH_EVENT__TYPE, test.nested.owext.Patches.PatchEvent::create); + } + + /** + * Explicit initialization for GWT or manual use. + */ + public static void init() { + new OwextTypes().register(); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/Patches.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/Patches.java new file mode 100644 index 00000000..0a9fbb77 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/Patches.java @@ -0,0 +1,89 @@ +package test.nested.owext; + +/** + * Nested extensions of a nested OpenWorld root declared in another file. + * + *

+ * No top-level definition of this file extends the OpenWorld root: the implied NoBinary must be + * detected from the nested extension. + *

+ */ +public interface Patches extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface PatchEvent extends test.nested.owbase.Events.Event { + + /** Extended visitor that can handle {@link PatchEvent}. */ + public interface Visitor extends test.nested.owbase.Events.Event.Visitor { + + /** Visit case for {@link PatchEvent}. */ + R visit(test.nested.owext.Patches.PatchEvent self, A arg) throws E; + + } + + /** + * Creates a {@link test.nested.owext.Patches.PatchEvent} instance. + */ + static test.nested.owext.Patches.PatchEvent create() { + return new test.nested.owext.impl.Patches_Impl.PatchEvent_Impl(); + } + + /** Identifier for the {@link test.nested.owext.Patches.PatchEvent} type in JSON format. */ + String PATCH_EVENT__TYPE = "PatchEvent"; + + /** @see #getPatch() */ + String PATCH__PROP = "patch"; + + String getPatch(); + + /** + * @see #getPatch() + */ + test.nested.owext.Patches.PatchEvent setPatch(String value); + + @Override + test.nested.owext.Patches.PatchEvent setTimestamp(long value); + + /** Reads a new instance from the given reader. */ + static test.nested.owext.Patches.PatchEvent readPatchEvent(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owext.impl.Patches_Impl.PatchEvent_Impl result = new test.nested.owext.impl.Patches_Impl.PatchEvent_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link PatchEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static PatchEvent readPatchEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owext.impl.Patches_Impl.PatchEvent_Impl.readPatchEvent_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.owext.Patches} instance. + */ + static test.nested.owext.Patches create() { + return new test.nested.owext.impl.Patches_Impl(); + } + + /** Identifier for the {@link test.nested.owext.Patches} type in JSON format. */ + String PATCHES__TYPE = "Patches"; + + @Override + public test.nested.owext.Patches registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.owext.Patches unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.owext.Patches readPatches(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.owext.impl.Patches_Impl result = new test.nested.owext.impl.Patches_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Patches} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Patches readPatches(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.owext.impl.Patches_Impl.readPatches_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/impl/Patches_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/impl/Patches_Impl.java new file mode 100644 index 00000000..ab4131b1 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/impl/Patches_Impl.java @@ -0,0 +1,306 @@ +package test.nested.owext.impl; + +/** + * Implementation of {@link test.nested.owext.Patches}. + */ +public class Patches_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.owext.Patches { + /** + * Implementation of {@link test.nested.owext.Patches.PatchEvent}. + */ + public static class PatchEvent_Impl extends test.nested.owbase.impl.Events_Impl.Event_Impl implements test.nested.owext.Patches.PatchEvent { + + private String _patch = ""; + + /** + * Creates a {@link PatchEvent_Impl} instance. + * + * @see test.nested.owext.Patches.PatchEvent#create() + */ + public PatchEvent_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final String getPatch() { + return _patch; + } + + @Override + public test.nested.owext.Patches.PatchEvent setPatch(String value) { + internalSetPatch(value); + return this; + } + + /** Internal setter for {@link #getPatch()} without chain call utility. */ + protected final void internalSetPatch(String value) { + _listener.beforeSet(this, PATCH__PROP, value); + _patch = value; + _listener.afterChanged(this, PATCH__PROP); + } + + @Override + public test.nested.owext.Patches.PatchEvent setTimestamp(long value) { + internalSetTimestamp(value); + return this; + } + + @Override + public String jsonType() { + return PATCH_EVENT__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + PATCH__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.owbase.impl.Events_Impl.Event_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case PATCH__PROP: return getPatch(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case PATCH__PROP: internalSetPatch((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(PATCH__PROP); + out.value(getPatch()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case PATCH__PROP: setPatch(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.owext.Patches.PatchEvent} type. */ + public static final String PATCH_EVENT__XML_ELEMENT = "patch-event"; + + /** XML attribute or element name of a {@link #getPatch} property. */ + private static final String PATCH__XML_ATTR = "patch"; + + @Override + public String getXmlTagName() { + return PATCH_EVENT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(PATCH__XML_ATTR, getPatch()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.owext.Patches.PatchEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static PatchEvent_Impl readPatchEvent_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + PatchEvent_Impl result = new PatchEvent_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case PATCH__XML_ATTR: { + setPatch(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case PATCH__XML_ATTR: { + setPatch(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.owbase.Events.Event.Visitor v, A arg) throws E { + if (v instanceof test.nested.owext.Patches.PatchEvent.Visitor) { + return ((test.nested.owext.Patches.PatchEvent.Visitor) v).visit(this, arg); + } + return v.visitDefault(this, arg); + } + + } + + /** + * Creates a {@link Patches_Impl} instance. + * + * @see test.nested.owext.Patches#create() + */ + public Patches_Impl() { + super(); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.owext.Patches registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.owext.Patches unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return PATCHES__TYPE; + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + /** XML element name representing a {@link test.nested.owext.Patches} type. */ + public static final String PATCHES__XML_ELEMENT = "patches"; + + @Override + public String getXmlTagName() { + return PATCHES__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.owext.Patches} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Patches_Impl readPatches_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Patches_Impl result = new Patches_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/owext.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/owext.proto new file mode 100644 index 00000000..1fd191d5 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/owext.proto @@ -0,0 +1,17 @@ +package test.nested.owext; + +import "../owbase/owbase.proto"; + +/** + * Nested extensions of a nested OpenWorld root declared in another file. + * + *

+ * No top-level definition of this file extends the OpenWorld root: the implied NoBinary must be + * detected from the nested extension. + *

+ */ +message Patches { + message PatchEvent extends test.nested.owbase.Events.Event { + string patch; + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/shapes.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/shapes.proto new file mode 100644 index 00000000..5741f41f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/shapes.proto @@ -0,0 +1,100 @@ +package test.nested.data; + +/** + * Hierarchies with an abstract root declared inside other messages (issue #16). + */ +message Outer { + /** Abstract root of a hierarchy nested in a top-level message. */ + abstract message Shape { + string name; + } + + message Circle extends Shape { + int32 radius; + } + + message Square extends Shape { + int32 side; + } + + /** A sibling message holding values of the nested abstract type. */ + message Drawing { + Shape main; + repeated Shape shapes; + } + + /** A field of the nested abstract type in the outer message itself. */ + Shape shape; +} + +/** + * A hierarchy nested two levels deep. + */ +message Level1 { + message Level2 { + abstract message Node { + string label; + } + + /** Abstract intermediate. */ + abstract message Composite extends Node { + repeated Node children; + } + + message Leaf extends Node { + int32 value; + } + + message Branch extends Composite { + bool expanded; + } + + message Root extends Composite { + string title; + } + } + + Level2.Node node; + repeated Level2.Node nodes; +} + +/** + * A top-level abstract root. + */ +abstract message Animal { + string name; +} + +/** + * A container for sub-messages extending a top-level abstract message. + */ +message Zoo { + message Cat extends Animal { + bool indoor; + } + + /** A nested abstract intermediate below a top-level root. */ + abstract message Bird extends Animal { + double wingspan; + } + + message Parrot extends Bird { + repeated string words; + } + + repeated Animal animals; +} + +/** A top-level message extending a nested abstract message. */ +message Triangle extends Outer.Shape { + int32 base; + int32 height; +} + +/** A top-level holder of values of nested abstract types. */ +message Holder { + Outer.Shape shape; + repeated Outer.Shape shapes; + Level1.Level2.Node node; + repeated Animal animals; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration index e8bcff82..a3eef857 100644 --- a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration +++ b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration @@ -1,2 +1,4 @@ test.openworld.ext1.Ext1Types +test.nested.owcount.OwcountTypes test.openworld.ext2.Ext2Types +test.nested.owext.OwextTypes From dc8ebcf5b68a1a712614070b46827a5190552659 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 15:52:44 +0200 Subject: [PATCH 05/20] Honor the format options for enums and reject cross-file references to disabled formats. `EnumGenerator` had no options and always emitted the JSON and binary methods, so `option NoBinary` and `option NoJson` did not apply to enums (#20). It now uses the same format rules as `MessageGenerator`, which gets the rules for both. With that change, a file that uses an enum of another file in a format that file disables would get uncompilable code. The same already happened on main for messages of such files and for references between SharedGraph and non-SharedGraph files. As decided by the maintainer, the generator now rejects these references in a validation stage before writing any code, naming both files and the option to change. It reports them in a `GeneratorException`; the CLI prints them and exits with status 1. The formats a field needs come from the generator for JSON and binary and from the new `GeneratorPlugin.addFormats()` / `addFieldFormats()` for plug-in formats. The XML plugin reports its actual behavior: it skips maps and, unlike JSON and binary, serializes transient fields (#29). Closes #20 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + README.md | 12 +- .../msgbuf/generator/EnumGenerator.java | 31 +- .../haumacher/msgbuf/generator/Generator.java | 191 +++++++++++- .../msgbuf/generator/GeneratorException.java | 36 +++ .../msgbuf/generator/GeneratorPlugin.java | 54 ++++ .../msgbuf/generator/MessageGenerator.java | 20 +- .../generator/plugins/XmlStreamingPlugin.java | 22 ++ .../test/enumoptions/TestEnumOptions.java | 79 +++++ .../enumoptions/TestFormatReferences.java | 89 ++++++ .../test/java/test/enumoptions/nobinary.proto | 18 ++ .../java/test/enumoptions/nobinary/M.java | 102 +++++++ .../test/enumoptions/nobinary/TopLevel.java | 46 +++ .../enumoptions/nobinary/impl/M_Impl.java | 254 ++++++++++++++++ .../test/java/test/enumoptions/nojson.proto | 18 ++ .../test/java/test/enumoptions/nojson/M.java | 117 ++++++++ .../test/enumoptions/nojson/TopLevel.java | 54 ++++ .../test/enumoptions/nojson/impl/M_Impl.java | 276 ++++++++++++++++++ .../java/test/enumoptions/sharedgraph.proto | 18 ++ .../java/test/enumoptions/sharedgraph/M.java | 104 +++++++ .../enumoptions/sharedgraph/TopLevel.java | 46 +++ .../enumoptions/sharedgraph/impl/M_Impl.java | 242 +++++++++++++++ .../reject/formats/colors/colors.proto | 13 + .../reject/formats/graph/graph.proto | 10 + .../reject/formats/paint/paint-nobinary.proto | 10 + .../reject/formats/paint/paint.proto | 14 + 26 files changed, 1871 insertions(+), 11 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestEnumOptions.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/M.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/TopLevel.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/impl/M_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/M.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/TopLevel.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/impl/M_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/M.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/TopLevel.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/impl/M_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/formats/colors/colors.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/formats/graph/graph.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint-nobinary.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bc58689..1d8e08c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,12 @@ their qualified names in the generated JSON and XML readers (previously uncompilable). For `option OpenWorld`, the "same file" test for local subtypes and the implied `NoBinary` of extension files now also hold for nested definitions. +- **Format options for enums** (#20): `option NoBinary` and `option NoJson` (and the implied `NoBinary` of + `option SharedGraph` and `option OpenWorld`) now also suppress the binary and JSON methods of enums. + **Source compatibility:** a file that uses an enum of another file in a format the other file disables did compile + before, because enums always had all methods. It is now rejected with an error naming both files and the option, + as are references to messages of such files and mixed `option SharedGraph` references, which generated uncompilable + code before. The generator (CLI and Maven plugin) now stops without writing code when it finds such errors. ## 1.2.1 diff --git a/README.md b/README.md index fe703035..30daccc2 100644 --- a/README.md +++ b/README.md @@ -196,14 +196,22 @@ For binary serialization, json values are wrapped in a `JsonValue` message envel ## Global protocol options ### `option NoJson` -Disables generation of read and write methods for the JSON format. +Disables generation of read and write methods for the JSON format (for messages and enums). ### `option NoBinary` -Disables generation of read and write methods for binary format. +Disables generation of read and write methods for binary format (for messages and enums). ### `option NoXml` Disables generation of read and write methods for XML format. +The format options apply to all messages and enums of a file. A message that references a message or enum of another +file (as field type or with `extends`) needs the read and write methods of each format it generates itself in that +other file. The generator rejects a reference to a definition generated without such a format, and generates no code +in that case. Either disable the format in the referencing file as well, or enable it in the referenced one. The same +holds for `option SharedGraph`, which has its own JSON methods for messages: a message can reference messages of +another file only if both files use `option SharedGraph`, or neither does. Enums are not affected by +`option SharedGraph`. `transient` fields are not written in JSON or binary format, so they don't need these formats. + ### `option NoXmlNames` Disables generation of constants for the XML format. diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java index 08d3dafd..cc14f4a1 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/EnumGenerator.java @@ -8,11 +8,13 @@ import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import de.haumacher.msgbuf.generator.ast.Constant; import de.haumacher.msgbuf.generator.ast.DefinitionFile; import de.haumacher.msgbuf.generator.ast.EnumDef; +import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.ast.QName; import de.haumacher.msgbuf.generator.common.MsgBufJsonProtocol; import de.haumacher.msgbuf.generator.util.AbstractJavaGenerator; @@ -25,13 +27,22 @@ public class EnumGenerator extends AbstractJavaGenerator { private EnumDef _def; + private final boolean _json; + + private final boolean _binary; + /** * Creates a {@link EnumGenerator}. * + * @param options + * The options of the file defining the enumeration, selecting the serialization formats. * @param def + * The enumeration to generate. */ - public EnumGenerator(EnumDef def) { + public EnumGenerator(Map options, EnumDef def) { _def = def; + _json = MessageGenerator.isJson(options); + _binary = MessageGenerator.isBinary(options); } @Override @@ -87,6 +98,17 @@ protected void generate() { } line("}"); + if (_json) { + generateJsonIO(); + } + if (_binary) { + generateBinaryIO(); + } + + line("}"); + } + + private void generateJsonIO() { nl(); line("/** Writes this instance to the given output. */"); line("public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException {"); @@ -102,7 +124,10 @@ protected void generate() { line("return " + CodeConvention.ENUM_VALUE_OF_PROTOCOL + "(in.nextString());"); } line("}"); - + } + + private void generateBinaryIO() { + List constants = _def.getConstants(); nl(); line("/** Writes this instance to the given binary output. */"); line("public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException {"); @@ -131,8 +156,6 @@ protected void generate() { line("}"); } line("}"); - - line("}"); } private void generateConstants() { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 194879f4..38565465 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -41,6 +41,7 @@ import de.haumacher.msgbuf.generator.parser.ProtobufParser; import de.haumacher.msgbuf.generator.parser.ProtobufParserConstants; import de.haumacher.msgbuf.generator.parser.Token; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; import de.haumacher.msgbuf.generator.ts.TypeScriptGenerator; import de.haumacher.msgbuf.generator.util.FileGenerator; @@ -182,6 +183,16 @@ public void generate(GeneratorPlugin plugin) { propagateOpenWorldOptions(file); } + List errors = new ArrayList<>(); + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file)) { + validateFormatReferences(file, plugin, errors); + } + } + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } + TypeIdSynthesizer typeIdSynthesizer = new TypeIdSynthesizer(); for (DefinitionFile file : _files) { if (!Util.getFlag(file, "OpenWorld")) { @@ -337,6 +348,175 @@ private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, List + * The generated read and write methods of a message call the corresponding methods of the + * messages and enums of its fields and of its generalization. If one of these is defined in + * another file that disables the format, the generated code would not compile. + *

+ */ + private void validateFormatReferences(DefinitionFile file, GeneratorPlugin plugin, List errors) { + for (Definition def : file.getDefinitions()) { + validateFormatReferences(file, def, plugin, errors); + } + } + + private void validateFormatReferences(DefinitionFile file, Definition def, GeneratorPlugin plugin, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + Set formats = formats(file, plugin); + + MessageDef extended = message.getExtendedDef(); + if (extended != null) { + checkFormats(file, formats, "Message '" + Util.toString(message) + "' extends", extended, plugin, errors); + } + + for (Field field : message.getFields()) { + Set fieldFormats = fieldFormats(file, field, plugin); + for (Definition target : referencedDefinitions(field.getType())) { + checkFormats(file, fieldFormats, + "Field '" + Util.toString(message) + "." + field.getName() + "' references", target, plugin, errors); + } + } + + for (Definition inner : message.getDefinitions()) { + validateFormatReferences(file, inner, plugin, errors); + } + } + + private void checkFormats(DefinitionFile file, Set formats, String reference, Definition target, + GeneratorPlugin plugin, List errors) { + DefinitionFile targetFile = Util.definingFile(target); + if (targetFile == file) { + return; + } + boolean isEnum = target instanceof EnumDef; + Set targetFormats = isEnum ? enumFormats(targetFile.getOptions()) : formats(targetFile, plugin); + String prefix = sourceDescription(file) + ": " + reference + (isEnum ? " enum '" : " message '") + + Util.toString(target) + "' of '" + sourceDescription(targetFile) + "'"; + for (String format : formats) { + if (isEnum) { + if (format.equals(GRAPH_JSON_FORMAT)) { + // The JSON methods of an enum do not depend on the graph mode. + format = JSON_FORMAT; + } else if (!format.equals(JSON_FORMAT) && !format.equals(BINARY_FORMAT)) { + // Enums are serialized in plug-in formats through their protocol names. + continue; + } + } + if (targetFormats.contains(format)) { + continue; + } + if (format.equals(GRAPH_JSON_FORMAT) || (format.equals(JSON_FORMAT) && targetFormats.contains(GRAPH_JSON_FORMAT))) { + errors.add(prefix + ", but only one of the files uses option SharedGraph. Use option SharedGraph in both" + + " files or in neither."); + } else { + errors.add(prefix + ", which is generated without " + format + " serialization (" + + disabledBy(targetFile, format) + "). Add 'option " + DISABLE_OPTION.get(format) + ";' to '" + + sourceDescription(file) + "', or enable " + format + " serialization in '" + + sourceDescription(targetFile) + "'."); + } + } + } + + private static final String JSON_FORMAT = "JSON"; + + /** + * JSON of the SharedGraph mode, which has its own read and write methods. + */ + private static final String GRAPH_JSON_FORMAT = "SharedGraph JSON"; + + private static final String BINARY_FORMAT = "binary"; + + private static final Map DISABLE_OPTION = + Map.of(JSON_FORMAT, "NoJson", BINARY_FORMAT, "NoBinary", XmlStreamingPlugin.XML_FORMAT, "NoXml"); + + private static Set formats(DefinitionFile file, GeneratorPlugin plugin) { + Set result = coreFormats(file.getOptions()); + plugin.addFormats(file.getOptions(), result); + return result; + } + + private static Set fieldFormats(DefinitionFile file, Field field, GeneratorPlugin plugin) { + Set result = new HashSet<>(); + if (!field.isTransient() && !field.isDerived()) { + result.addAll(coreFormats(file.getOptions())); + } + plugin.addFieldFormats(file.getOptions(), field, result); + return result; + } + + /** + * The formats of the generated read and write methods of messages. + */ + private static Set coreFormats(Map options) { + Set result = new HashSet<>(); + if (MessageGenerator.isJson(options)) { + result.add(MessageGenerator.isTrue(options.get("SharedGraph"), false) ? GRAPH_JSON_FORMAT : JSON_FORMAT); + } + if (MessageGenerator.isBinary(options)) { + result.add(BINARY_FORMAT); + } + return result; + } + + /** + * The formats of the generated read and write methods of enums. + */ + private static Set enumFormats(Map options) { + Set result = new HashSet<>(); + if (MessageGenerator.isJson(options)) { + result.add(JSON_FORMAT); + } + if (MessageGenerator.isBinary(options)) { + result.add(BINARY_FORMAT); + } + return result; + } + + private static String disabledBy(DefinitionFile file, String format) { + if (format.equals(BINARY_FORMAT)) { + if (Util.getFlag(file, "SharedGraph")) { + return "option SharedGraph"; + } + if (Util.getFlag(file, "OpenWorld")) { + return "option OpenWorld implies NoBinary"; + } + } + return "option " + DISABLE_OPTION.get(format); + } + + private static List referencedDefinitions(Type type) { + List result = new ArrayList<>(); + type.visit(new Type.Visitor() { + @Override + public Void visit(CustomType self, Void arg) { + if (self.getDefinition() != null) { + result.add(self.getDefinition()); + } + return null; + } + + @Override + public Void visit(PrimitiveType self, Void arg) { + return null; + } + + @Override + public Void visit(MapType self, Void arg) { + self.getKeyType().visit(this, arg); + self.getValueType().visit(this, arg); + return null; + } + }, null); + return result; + } + private void resolveImports(DefinitionFile file, File sourceFile) throws IOException, ParseException { for (String importPath : file.getImports()) { // Try file system first @@ -613,7 +793,7 @@ public PackageGenerator(File dir, Map options, GeneratorPlugin p @Override public Void visit(EnumDef def, Void arg) { - return generateJava(CodeConvention.typeName(def), null, new EnumGenerator(def)); + return generateJava(CodeConvention.typeName(def), null, new EnumGenerator(_options, def)); } @Override @@ -715,7 +895,14 @@ public static void main(String... args) throws ParseException, IOException, Inst generator.setOut(out); } - generator.generate(loadPlugins()); + try { + generator.generate(loadPlugins()); + } catch (GeneratorException ex) { + for (String error : ex.getErrors()) { + System.err.println("ERROR: " + error); + } + System.exit(1); + } } /** diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java new file mode 100644 index 00000000..7df8fecb --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorException.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package de.haumacher.msgbuf.generator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Rejection of the input definitions: code generation was not started, because the definitions + * are invalid. + */ +public class GeneratorException extends RuntimeException { + + private final List _errors; + + /** + * Creates a {@link GeneratorException}. + * + * @param errors + * The problems found, each naming the file and the definition concerned. + */ + public GeneratorException(List errors) { + super(String.join("\n", errors)); + _errors = Collections.unmodifiableList(new ArrayList<>(errors)); + } + + /** + * The problems found, each naming the file and the definition concerned. + */ + public List getErrors() { + return _errors; + } + +} diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java index b27322bb..a96a328d 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java @@ -5,7 +5,9 @@ import java.util.List; import java.util.Map; +import java.util.Set; +import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.util.FileGenerator; @@ -58,6 +60,46 @@ default FileGenerator messageImplContents(Map options, MessageDe return (out, indent) -> {/*ignore*/}; } + /** + * Adds the names of the serialization formats this plug-in generates code for. + * + *

+ * A message referencing a message of another file requires all formats of its own file in the + * other file, since its generated code calls the other message's generated read and write + * methods. + *

+ * + * @param options + * The options of a definition file. + * @param formats + * The set of format names to add to. + */ + default void addFormats(Map options, Set formats) { + // No additional formats by default. + } + + /** + * Adds the names of the serialization formats in which the code generated by this plug-in + * writes and reads the value of the given field. + * + *

+ * If the field references a message or enum of another file, that file must generate code for + * these formats. + *

+ * + * @param options + * The options of the file defining the field. + * @param field + * The field to check. + * @param formats + * The set of format names to add to. + * + * @see #addFormats(Map, Set) + */ + default void addFieldFormats(Map options, Field field, Set formats) { + // No additional formats by default. + } + /** * {@link GeneratorPlugin} that does not generate any output. */ @@ -88,6 +130,18 @@ public void addInterfaces(Map options, MessageDef def, List options, Set formats) { + self.addFormats(options, formats); + next.addFormats(options, formats); + } + + @Override + public void addFieldFormats(Map options, Field field, Set formats) { + self.addFieldFormats(options, field, formats); + next.addFieldFormats(options, field, formats); + } @Override public FileGenerator messageImplContents(Map options, MessageDef def) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index 853c60f6..4804f3a0 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -66,8 +66,8 @@ public MessageGenerator(NameTable table, Map options, boolean is _plugin = plugin; _defaultValues = new DefaultValueGenerator(options); _graph = isTrue(options.get("SharedGraph"), false); - _json = _graph || !isTrue(options.get("NoJson"), false); - _binary = !_graph && !isTrue(options.get("NoBinary"), false); + _json = isJson(options); + _binary = isBinary(options); _listener = _graph || !isTrue(options.get("NoListener"), false); _reflection = _listener || !isTrue(options.get("NoReflection"), false); _visitor = !isTrue(options.get("NoVisitor"), false); @@ -434,10 +434,24 @@ private void generateInnerDefinitions() { } } + /** + * Whether JSON serialization code is generated for the given file options. + */ + public static boolean isJson(Map options) { + return isTrue(options.get("SharedGraph"), false) || !isTrue(options.get("NoJson"), false); + } + + /** + * Whether binary serialization code is generated for the given file options. + */ + public static boolean isBinary(Map options) { + return !isTrue(options.get("SharedGraph"), false) && !isTrue(options.get("NoBinary"), false); + } + @Override public Void visit(EnumDef def, Void arg) { if (_interface || _noInterfaces) { - include(new EnumGenerator(def)); + include(new EnumGenerator(getOptions(), def)); } return null; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index bac45eef..0a2d1068 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -32,6 +32,13 @@ * {@link GeneratorPlugin} generating XML reading code for the {@link javax.xml.stream.XMLStreamReader} interface. */ public class XmlStreamingPlugin implements GeneratorPlugin { + + /** + * Name of the XML format. + * + * @see #addFormats(Map, Set) + */ + public static final String XML_FORMAT = "XML"; private boolean _noXmlNames; @@ -40,6 +47,21 @@ public void init(Map options) { _noXmlNames = noXmlNames(options); } + @Override + public void addFormats(Map options, Set formats) { + if (!noXml(options)) { + formats.add(XML_FORMAT); + } + } + + @Override + public void addFieldFormats(Map options, Field field, Set formats) { + // All fields except maps are written and read, including transient ones. + if (!noXml(options) && field.getType().kind() != Type.TypeKind.MAP_TYPE) { + formats.add(XML_FORMAT); + } + } + @Override public void addInterfaces(Map options, MessageDef def, List generalizations) { if (noXml(options)) { diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestEnumOptions.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestEnumOptions.java new file mode 100644 index 00000000..4d2c9b3d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestEnumOptions.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.enumoptions; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; + +import de.haumacher.msgbuf.binary.DataReader; +import de.haumacher.msgbuf.binary.DataWriter; +import de.haumacher.msgbuf.binary.OctetDataReader; +import de.haumacher.msgbuf.binary.OctetDataWriter; +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import de.haumacher.msgbuf.json.JsonWriter; +import junit.framework.TestCase; + +/** + * Test case for enums honoring the serialization options of their file, like messages do (issue #20). + */ +@SuppressWarnings("javadoc") +public class TestEnumOptions extends TestCase { + + public void testNoBinary() throws IOException { + assertFormats(test.enumoptions.nobinary.M.Nested.class, true, false); + assertFormats(test.enumoptions.nobinary.TopLevel.class, true, false); + + test.enumoptions.nobinary.M value = test.enumoptions.nobinary.M.create() + .setNested(test.enumoptions.nobinary.M.Nested.B) + .setTop(test.enumoptions.nobinary.TopLevel.Y); + String json = value.toString(); + assertEquals("{\"nested\":\"B\",\"top\":\"Y\"}", json); + test.enumoptions.nobinary.M copy = test.enumoptions.nobinary.M.readM(new JsonReader(new StringR(json))); + assertEquals(test.enumoptions.nobinary.M.Nested.B, copy.getNested()); + assertEquals(test.enumoptions.nobinary.TopLevel.Y, copy.getTop()); + } + + public void testNoJson() throws IOException { + assertFormats(test.enumoptions.nojson.M.Nested.class, false, true); + assertFormats(test.enumoptions.nojson.TopLevel.class, false, true); + + test.enumoptions.nojson.M value = test.enumoptions.nojson.M.create() + .setNested(test.enumoptions.nojson.M.Nested.B) + .setTop(test.enumoptions.nojson.TopLevel.Y); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + value.writeTo(new OctetDataWriter(buffer)); + test.enumoptions.nojson.M copy = test.enumoptions.nojson.M.readM( + new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))); + assertEquals(test.enumoptions.nojson.M.Nested.B, copy.getNested()); + assertEquals(test.enumoptions.nojson.TopLevel.Y, copy.getTop()); + } + + public void testSharedGraph() { + // SharedGraph implies JSON and excludes binary. + assertFormats(test.enumoptions.sharedgraph.M.Nested.class, true, false); + assertFormats(test.enumoptions.sharedgraph.TopLevel.class, true, false); + } + + private static void assertFormats(Class> type, boolean json, boolean binary) { + String name = type.getSimpleName(); + assertEquals("JSON writer of " + name, json, hasMethod(type, "writeTo", JsonWriter.class)); + assertEquals("JSON reader of " + name, json, hasMethod(type, "read" + name, JsonReader.class)); + assertEquals("Binary writer of " + name, binary, hasMethod(type, "writeTo", DataWriter.class)); + assertEquals("Binary reader of " + name, binary, hasMethod(type, "read" + name, DataReader.class)); + } + + private static boolean hasMethod(Class type, String name, Class parameterType) { + for (Method method : type.getMethods()) { + if (method.getName().equals(name) && method.getParameterCount() == 1 + && method.getParameterTypes()[0] == parameterType) { + return true; + } + } + return false; + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java new file mode 100644 index 00000000..a79b9e01 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.enumoptions; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +import de.haumacher.msgbuf.generator.Generator; +import de.haumacher.msgbuf.generator.GeneratorException; +import de.haumacher.msgbuf.generator.parser.ParseException; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; +import junit.framework.TestCase; + +/** + * Test case for rejecting references to definitions of other files that are generated without a + * serialization format the referencing file needs (issue #20). + */ +@SuppressWarnings("javadoc") +public class TestFormatReferences extends TestCase { + + private static final File FIXTURES = new File("src/test/resources/reject/formats"); + + public void testRejectMissingBinary() throws IOException, ParseException { + List errors = reject("paint/paint.proto"); + assertEquals(Arrays.asList( + "reject/formats/paint/paint.proto: Field 'reject.formats.paint.Paint.color' references enum" + + " 'reject.formats.colors.Color' of 'reject/formats/colors/colors.proto', which is generated without" + + " binary serialization (option NoBinary). Add 'option NoBinary;' to" + + " 'reject/formats/paint/paint.proto', or enable binary serialization in" + + " 'reject/formats/colors/colors.proto'.", + "reject/formats/paint/paint.proto: Field 'reject.formats.paint.Paint.shades' references message" + + " 'reject.formats.colors.Shade' of 'reject/formats/colors/colors.proto', which is generated without" + + " binary serialization (option NoBinary). Add 'option NoBinary;' to" + + " 'reject/formats/paint/paint.proto', or enable binary serialization in" + + " 'reject/formats/colors/colors.proto'.", + "reject/formats/paint/paint.proto: Field 'reject.formats.paint.Paint.Layer.colors' references enum" + + " 'reject.formats.colors.Color' of 'reject/formats/colors/colors.proto', which is generated without" + + " binary serialization (option NoBinary). Add 'option NoBinary;' to" + + " 'reject/formats/paint/paint.proto', or enable binary serialization in" + + " 'reject/formats/colors/colors.proto'."), + errors); + } + + public void testRejectSharedGraphMismatch() throws IOException, ParseException { + List errors = reject("graph/graph.proto"); + assertEquals(Arrays.asList( + "reject/formats/graph/graph.proto: Field 'reject.formats.graph.Node.shade' references message" + + " 'reject.formats.colors.Shade' of 'reject/formats/colors/colors.proto', but only one of the files" + + " uses option SharedGraph. Use option SharedGraph in both files or in neither."), + errors); + } + + public void testAcceptMatchingFormats() throws IOException, ParseException { + File out = newOutputDir(); + generator(out, "paint/paint-nobinary.proto").generate(new XmlStreamingPlugin()); + assertTrue(new File(out, "reject/formats/paint/PaintNoBinary.java").isFile()); + } + + private List reject(String proto) throws IOException, ParseException { + File out = newOutputDir(); + try { + generator(out, proto).generate(new XmlStreamingPlugin()); + fail("Expected rejection of '" + proto + "'."); + return null; + } catch (GeneratorException ex) { + String[] written = out.list(); + assertTrue("No code must be generated for rejected definitions.", written == null || written.length == 0); + return ex.getErrors(); + } + } + + private static Generator generator(File out, String proto) throws IOException, ParseException { + Generator generator = new Generator(); + generator.setOut(out); + generator.load(new File(FIXTURES, proto)); + return generator; + } + + private File newOutputDir() throws IOException { + File target = new File("target"); + target.mkdirs(); + return Files.createTempDirectory(target.toPath(), getName()).toFile(); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary.proto b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary.proto new file mode 100644 index 00000000..9ddc7e27 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary.proto @@ -0,0 +1,18 @@ +package test.enumoptions.nobinary; + +option NoBinary; + +/** Enums honor `option NoBinary` like messages do (issue #20). */ +message M { + enum Nested { + A; + B; + } + Nested nested; + TopLevel top; +} + +enum TopLevel { + X; + Y; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/M.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/M.java new file mode 100644 index 00000000..1e965591 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/M.java @@ -0,0 +1,102 @@ +package test.enumoptions.nobinary; + +/** + * Enums honor `option NoBinary` like messages do (issue #20). + */ +public interface M extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + public enum Nested implements de.haumacher.msgbuf.data.ProtocolEnum { + + A("A"), + + B("B"), + + ; + + private final String _protocolName; + + private Nested(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link Nested} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link Nested} constant by it's protocol name. */ + public static Nested valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "A": return A; + case "B": return B; + } + return A; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static Nested readNested(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } + } + + /** + * Creates a {@link test.enumoptions.nobinary.M} instance. + */ + static test.enumoptions.nobinary.M create() { + return new test.enumoptions.nobinary.impl.M_Impl(); + } + + /** Identifier for the {@link test.enumoptions.nobinary.M} type in JSON format. */ + String M__TYPE = "M"; + + /** @see #getNested() */ + String NESTED__PROP = "nested"; + + /** @see #getTop() */ + String TOP__PROP = "top"; + + test.enumoptions.nobinary.M.Nested getNested(); + + /** + * @see #getNested() + */ + test.enumoptions.nobinary.M setNested(test.enumoptions.nobinary.M.Nested value); + + test.enumoptions.nobinary.TopLevel getTop(); + + /** + * @see #getTop() + */ + test.enumoptions.nobinary.M setTop(test.enumoptions.nobinary.TopLevel value); + + @Override + public test.enumoptions.nobinary.M registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.enumoptions.nobinary.M unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.enumoptions.nobinary.M readM(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.enumoptions.nobinary.impl.M_Impl result = new test.enumoptions.nobinary.impl.M_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M readM(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.enumoptions.nobinary.impl.M_Impl.readM_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/TopLevel.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/TopLevel.java new file mode 100644 index 00000000..b86d5e69 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/TopLevel.java @@ -0,0 +1,46 @@ +package test.enumoptions.nobinary; + +public enum TopLevel implements de.haumacher.msgbuf.data.ProtocolEnum { + + X("X"), + + Y("Y"), + + ; + + private final String _protocolName; + + private TopLevel(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link TopLevel} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link TopLevel} constant by it's protocol name. */ + public static TopLevel valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "X": return X; + case "Y": return Y; + } + return X; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static TopLevel readTopLevel(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/impl/M_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/impl/M_Impl.java new file mode 100644 index 00000000..0a8c89f2 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nobinary/impl/M_Impl.java @@ -0,0 +1,254 @@ +package test.enumoptions.nobinary.impl; + +/** + * Implementation of {@link test.enumoptions.nobinary.M}. + */ +public class M_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.enumoptions.nobinary.M { + + private test.enumoptions.nobinary.M.Nested _nested = test.enumoptions.nobinary.M.Nested.A; + + private test.enumoptions.nobinary.TopLevel _top = test.enumoptions.nobinary.TopLevel.X; + + /** + * Creates a {@link M_Impl} instance. + * + * @see test.enumoptions.nobinary.M#create() + */ + public M_Impl() { + super(); + } + + @Override + public final test.enumoptions.nobinary.M.Nested getNested() { + return _nested; + } + + @Override + public test.enumoptions.nobinary.M setNested(test.enumoptions.nobinary.M.Nested value) { + internalSetNested(value); + return this; + } + + /** Internal setter for {@link #getNested()} without chain call utility. */ + protected final void internalSetNested(test.enumoptions.nobinary.M.Nested value) { + if (value == null) throw new IllegalArgumentException("Property 'nested' cannot be null."); + _listener.beforeSet(this, NESTED__PROP, value); + _nested = value; + _listener.afterChanged(this, NESTED__PROP); + } + + @Override + public final test.enumoptions.nobinary.TopLevel getTop() { + return _top; + } + + @Override + public test.enumoptions.nobinary.M setTop(test.enumoptions.nobinary.TopLevel value) { + internalSetTop(value); + return this; + } + + /** Internal setter for {@link #getTop()} without chain call utility. */ + protected final void internalSetTop(test.enumoptions.nobinary.TopLevel value) { + if (value == null) throw new IllegalArgumentException("Property 'top' cannot be null."); + _listener.beforeSet(this, TOP__PROP, value); + _top = value; + _listener.afterChanged(this, TOP__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.enumoptions.nobinary.M registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.enumoptions.nobinary.M unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return M__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NESTED__PROP, + TOP__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NESTED__PROP: return getNested(); + case TOP__PROP: return getTop(); + default: return test.enumoptions.nobinary.M.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NESTED__PROP: internalSetNested((test.enumoptions.nobinary.M.Nested) value); break; + case TOP__PROP: internalSetTop((test.enumoptions.nobinary.TopLevel) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NESTED__PROP); + getNested().writeTo(out); + out.name(TOP__PROP); + getTop().writeTo(out); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NESTED__PROP: setNested(test.enumoptions.nobinary.M.Nested.readNested(in)); break; + case TOP__PROP: setTop(test.enumoptions.nobinary.TopLevel.readTopLevel(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.enumoptions.nobinary.M} type. */ + public static final String M__XML_ELEMENT = "m"; + + /** XML attribute or element name of a {@link #getNested} property. */ + private static final String NESTED__XML_ATTR = "nested"; + + /** XML attribute or element name of a {@link #getTop} property. */ + private static final String TOP__XML_ATTR = "top"; + + @Override + public String getXmlTagName() { + return M__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NESTED__XML_ATTR, getNested().protocolName()); + out.writeAttribute(TOP__XML_ATTR, getTop().protocolName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.enumoptions.nobinary.M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M_Impl readM_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + M_Impl result = new M_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.nobinary.M.Nested.valueOfProtocol(value)); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.nobinary.TopLevel.valueOfProtocol(value)); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.nobinary.M.Nested.valueOfProtocol(in.getElementText())); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.nobinary.TopLevel.valueOfProtocol(in.getElementText())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson.proto b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson.proto new file mode 100644 index 00000000..dd2c6d8e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson.proto @@ -0,0 +1,18 @@ +package test.enumoptions.nojson; + +option NoJson; + +/** Enums honor `option NoJson` like messages do (issue #20). */ +message M { + enum Nested { + A; + B; + } + Nested nested; + TopLevel top; +} + +enum TopLevel { + X; + Y; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/M.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/M.java new file mode 100644 index 00000000..90127067 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/M.java @@ -0,0 +1,117 @@ +package test.enumoptions.nojson; + +/** + * Enums honor `option NoJson` like messages do (issue #20). + */ +public interface M extends de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + public enum Nested implements de.haumacher.msgbuf.data.ProtocolEnum { + + A("A"), + + B("B"), + + ; + + private final String _protocolName; + + private Nested(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link Nested} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link Nested} constant by it's protocol name. */ + public static Nested valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "A": return A; + case "B": return B; + } + return A; + } + + /** Writes this instance to the given binary output. */ + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + switch (this) { + case A: out.value(1); break; + case B: out.value(2); break; + default: out.value(0); + } + } + + /** Reads a new instance from the given binary reader. */ + public static Nested readNested(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + switch (in.nextInt()) { + case 1: return A; + case 2: return B; + default: return A; + } + } + } + + /** + * Creates a {@link test.enumoptions.nojson.M} instance. + */ + static test.enumoptions.nojson.M create() { + return new test.enumoptions.nojson.impl.M_Impl(); + } + + /** Identifier for the {@link test.enumoptions.nojson.M} type in JSON format. */ + String M__TYPE = "M"; + + /** @see #getNested() */ + String NESTED__PROP = "nested"; + + /** @see #getTop() */ + String TOP__PROP = "top"; + + /** Identifier for the property {@link #getNested()} in binary format. */ + static final int NESTED__ID = 1; + + /** Identifier for the property {@link #getTop()} in binary format. */ + static final int TOP__ID = 2; + + test.enumoptions.nojson.M.Nested getNested(); + + /** + * @see #getNested() + */ + test.enumoptions.nojson.M setNested(test.enumoptions.nojson.M.Nested value); + + test.enumoptions.nojson.TopLevel getTop(); + + /** + * @see #getTop() + */ + test.enumoptions.nojson.M setTop(test.enumoptions.nojson.TopLevel value); + + @Override + public test.enumoptions.nojson.M registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.enumoptions.nojson.M unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.enumoptions.nojson.M readM(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.enumoptions.nojson.M result = test.enumoptions.nojson.impl.M_Impl.readM_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M readM(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.enumoptions.nojson.impl.M_Impl.readM_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/TopLevel.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/TopLevel.java new file mode 100644 index 00000000..2452fbf0 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/TopLevel.java @@ -0,0 +1,54 @@ +package test.enumoptions.nojson; + +public enum TopLevel implements de.haumacher.msgbuf.data.ProtocolEnum { + + X("X"), + + Y("Y"), + + ; + + private final String _protocolName; + + private TopLevel(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link TopLevel} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link TopLevel} constant by it's protocol name. */ + public static TopLevel valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "X": return X; + case "Y": return Y; + } + return X; + } + + /** Writes this instance to the given binary output. */ + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + switch (this) { + case X: out.value(1); break; + case Y: out.value(2); break; + default: out.value(0); + } + } + + /** Reads a new instance from the given binary reader. */ + public static TopLevel readTopLevel(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + switch (in.nextInt()) { + case 1: return X; + case 2: return Y; + default: return X; + } + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/impl/M_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/impl/M_Impl.java new file mode 100644 index 00000000..aef7bc47 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/nojson/impl/M_Impl.java @@ -0,0 +1,276 @@ +package test.enumoptions.nojson.impl; + +/** + * Implementation of {@link test.enumoptions.nojson.M}. + */ +public class M_Impl implements test.enumoptions.nojson.M { + + private test.enumoptions.nojson.M.Nested _nested = test.enumoptions.nojson.M.Nested.A; + + private test.enumoptions.nojson.TopLevel _top = test.enumoptions.nojson.TopLevel.X; + + /** + * Creates a {@link M_Impl} instance. + * + * @see test.enumoptions.nojson.M#create() + */ + public M_Impl() { + super(); + } + + @Override + public final test.enumoptions.nojson.M.Nested getNested() { + return _nested; + } + + @Override + public test.enumoptions.nojson.M setNested(test.enumoptions.nojson.M.Nested value) { + internalSetNested(value); + return this; + } + + /** Internal setter for {@link #getNested()} without chain call utility. */ + protected final void internalSetNested(test.enumoptions.nojson.M.Nested value) { + if (value == null) throw new IllegalArgumentException("Property 'nested' cannot be null."); + _listener.beforeSet(this, NESTED__PROP, value); + _nested = value; + _listener.afterChanged(this, NESTED__PROP); + } + + @Override + public final test.enumoptions.nojson.TopLevel getTop() { + return _top; + } + + @Override + public test.enumoptions.nojson.M setTop(test.enumoptions.nojson.TopLevel value) { + internalSetTop(value); + return this; + } + + /** Internal setter for {@link #getTop()} without chain call utility. */ + protected final void internalSetTop(test.enumoptions.nojson.TopLevel value) { + if (value == null) throw new IllegalArgumentException("Property 'top' cannot be null."); + _listener.beforeSet(this, TOP__PROP, value); + _top = value; + _listener.afterChanged(this, TOP__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.enumoptions.nojson.M registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.enumoptions.nojson.M unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return M__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NESTED__PROP, + TOP__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NESTED__PROP: return getNested(); + case TOP__PROP: return getTop(); + default: return test.enumoptions.nojson.M.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NESTED__PROP: internalSetNested((test.enumoptions.nojson.M.Nested) value); break; + case TOP__PROP: internalSetTop((test.enumoptions.nojson.TopLevel) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(NESTED__ID); + getNested().writeTo(out); + out.name(TOP__ID); + getTop().writeTo(out); + } + + /** Helper for creating an object of type {@link test.enumoptions.nojson.M} from a polymorphic composition. */ + public static test.enumoptions.nojson.M readM_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.enumoptions.nojson.impl.M_Impl result = new M_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case NESTED__ID: setNested(test.enumoptions.nojson.M.Nested.readNested(in)); break; + case TOP__ID: setTop(test.enumoptions.nojson.TopLevel.readTopLevel(in)); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.enumoptions.nojson.M} type. */ + public static final String M__XML_ELEMENT = "m"; + + /** XML attribute or element name of a {@link #getNested} property. */ + private static final String NESTED__XML_ATTR = "nested"; + + /** XML attribute or element name of a {@link #getTop} property. */ + private static final String TOP__XML_ATTR = "top"; + + @Override + public String getXmlTagName() { + return M__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NESTED__XML_ATTR, getNested().protocolName()); + out.writeAttribute(TOP__XML_ATTR, getTop().protocolName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.enumoptions.nojson.M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M_Impl readM_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + M_Impl result = new M_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.nojson.M.Nested.valueOfProtocol(value)); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.nojson.TopLevel.valueOfProtocol(value)); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.nojson.M.Nested.valueOfProtocol(in.getElementText())); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.nojson.TopLevel.valueOfProtocol(in.getElementText())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph.proto b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph.proto new file mode 100644 index 00000000..8fc7aefd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph.proto @@ -0,0 +1,18 @@ +package test.enumoptions.sharedgraph; + +option SharedGraph; + +/** Enums honor `option SharedGraph` like messages do (issue #20). */ +message M { + enum Nested { + A; + B; + } + Nested nested; + TopLevel top; +} + +enum TopLevel { + X; + Y; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/M.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/M.java new file mode 100644 index 00000000..8f9cc85c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/M.java @@ -0,0 +1,104 @@ +package test.enumoptions.sharedgraph; + +/** + * Enums honor `option SharedGraph` like messages do (issue #20). + */ +public interface M extends de.haumacher.msgbuf.graph.SharedGraphNode, de.haumacher.msgbuf.xml.XmlSerializable { + + public enum Nested implements de.haumacher.msgbuf.data.ProtocolEnum { + + A("A"), + + B("B"), + + ; + + private final String _protocolName; + + private Nested(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link Nested} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link Nested} constant by it's protocol name. */ + public static Nested valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "A": return A; + case "B": return B; + } + return A; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static Nested readNested(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } + } + + /** + * Creates a {@link test.enumoptions.sharedgraph.M} instance. + */ + static test.enumoptions.sharedgraph.M create() { + return new test.enumoptions.sharedgraph.impl.M_Impl(); + } + + /** Identifier for the {@link test.enumoptions.sharedgraph.M} type in JSON format. */ + String M__TYPE = "M"; + + /** @see #getNested() */ + String NESTED__PROP = "nested"; + + /** @see #getTop() */ + String TOP__PROP = "top"; + + test.enumoptions.sharedgraph.M.Nested getNested(); + + /** + * @see #getNested() + */ + test.enumoptions.sharedgraph.M setNested(test.enumoptions.sharedgraph.M.Nested value); + + test.enumoptions.sharedgraph.TopLevel getTop(); + + /** + * @see #getTop() + */ + test.enumoptions.sharedgraph.M setTop(test.enumoptions.sharedgraph.TopLevel value); + + /** Reads a new instance from the given reader. */ + static test.enumoptions.sharedgraph.M readM(de.haumacher.msgbuf.graph.Scope scope, de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + if (in.peek() == de.haumacher.msgbuf.json.JsonToken.NUMBER) { + return (test.enumoptions.sharedgraph.M) scope.resolveOrFail(in.nextInt()); + } + in.beginArray(); + String type = in.nextString(); + assert M__TYPE.equals(type); + int id = in.nextInt(); + test.enumoptions.sharedgraph.impl.M_Impl result = new test.enumoptions.sharedgraph.impl.M_Impl(); + scope.readData(result, id, in); + in.endArray(); + return result; + } + + /** Creates a new {@link M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M readM(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.enumoptions.sharedgraph.impl.M_Impl.readM_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/TopLevel.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/TopLevel.java new file mode 100644 index 00000000..32ab400b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/TopLevel.java @@ -0,0 +1,46 @@ +package test.enumoptions.sharedgraph; + +public enum TopLevel implements de.haumacher.msgbuf.data.ProtocolEnum { + + X("X"), + + Y("Y"), + + ; + + private final String _protocolName; + + private TopLevel(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link TopLevel} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link TopLevel} constant by it's protocol name. */ + public static TopLevel valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "X": return X; + case "Y": return Y; + } + return X; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static TopLevel readTopLevel(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/impl/M_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/impl/M_Impl.java new file mode 100644 index 00000000..2baa7cd3 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/sharedgraph/impl/M_Impl.java @@ -0,0 +1,242 @@ +package test.enumoptions.sharedgraph.impl; + +/** + * Implementation of {@link test.enumoptions.sharedgraph.M}. + */ +public class M_Impl extends de.haumacher.msgbuf.graph.AbstractSharedGraphNode implements test.enumoptions.sharedgraph.M { + + private test.enumoptions.sharedgraph.M.Nested _nested = test.enumoptions.sharedgraph.M.Nested.A; + + private test.enumoptions.sharedgraph.TopLevel _top = test.enumoptions.sharedgraph.TopLevel.X; + + /** + * Creates a {@link M_Impl} instance. + * + * @see test.enumoptions.sharedgraph.M#create() + */ + public M_Impl() { + super(); + } + + @Override + public final test.enumoptions.sharedgraph.M.Nested getNested() { + return _nested; + } + + @Override + public test.enumoptions.sharedgraph.M setNested(test.enumoptions.sharedgraph.M.Nested value) { + internalSetNested(value); + return this; + } + + /** Internal setter for {@link #getNested()} without chain call utility. */ + protected final void internalSetNested(test.enumoptions.sharedgraph.M.Nested value) { + if (value == null) throw new IllegalArgumentException("Property 'nested' cannot be null."); + _listener.beforeSet(this, NESTED__PROP, value); + _nested = value; + _listener.afterChanged(this, NESTED__PROP); + } + + @Override + public final test.enumoptions.sharedgraph.TopLevel getTop() { + return _top; + } + + @Override + public test.enumoptions.sharedgraph.M setTop(test.enumoptions.sharedgraph.TopLevel value) { + internalSetTop(value); + return this; + } + + /** Internal setter for {@link #getTop()} without chain call utility. */ + protected final void internalSetTop(test.enumoptions.sharedgraph.TopLevel value) { + if (value == null) throw new IllegalArgumentException("Property 'top' cannot be null."); + _listener.beforeSet(this, TOP__PROP, value); + _top = value; + _listener.afterChanged(this, TOP__PROP); + } + + @Override + public String jsonType() { + return M__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NESTED__PROP, + TOP__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NESTED__PROP: return getNested(); + case TOP__PROP: return getTop(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NESTED__PROP: internalSetNested((test.enumoptions.sharedgraph.M.Nested) value); break; + case TOP__PROP: internalSetTop((test.enumoptions.sharedgraph.TopLevel) value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.graph.Scope scope, de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(scope, out); + out.name(NESTED__PROP); + getNested().writeTo(out); + out.name(TOP__PROP); + getTop().writeTo(out); + } + + @Override + public void writeFieldValue(de.haumacher.msgbuf.graph.Scope scope, de.haumacher.msgbuf.json.JsonWriter out, String field) throws java.io.IOException { + switch (field) { + case NESTED__PROP: { + getNested().writeTo(out); + break; + } + case TOP__PROP: { + getTop().writeTo(out); + break; + } + default: super.writeFieldValue(scope, out, field); + } + } + + @Override + public void readField(de.haumacher.msgbuf.graph.Scope scope, de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NESTED__PROP: setNested(test.enumoptions.sharedgraph.M.Nested.readNested(in)); break; + case TOP__PROP: setTop(test.enumoptions.sharedgraph.TopLevel.readTopLevel(in)); break; + default: super.readField(scope, in, field); + } + } + + /** XML element name representing a {@link test.enumoptions.sharedgraph.M} type. */ + public static final String M__XML_ELEMENT = "m"; + + /** XML attribute or element name of a {@link #getNested} property. */ + private static final String NESTED__XML_ATTR = "nested"; + + /** XML attribute or element name of a {@link #getTop} property. */ + private static final String TOP__XML_ATTR = "top"; + + @Override + public String getXmlTagName() { + return M__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NESTED__XML_ATTR, getNested().protocolName()); + out.writeAttribute(TOP__XML_ATTR, getTop().protocolName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.enumoptions.sharedgraph.M} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static M_Impl readM_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + M_Impl result = new M_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.sharedgraph.M.Nested.valueOfProtocol(value)); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.sharedgraph.TopLevel.valueOfProtocol(value)); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NESTED__XML_ATTR: { + setNested(test.enumoptions.sharedgraph.M.Nested.valueOfProtocol(in.getElementText())); + break; + } + case TOP__XML_ATTR: { + setTop(test.enumoptions.sharedgraph.TopLevel.valueOfProtocol(in.getElementText())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/colors/colors.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/colors/colors.proto new file mode 100644 index 00000000..4c34f3c9 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/colors/colors.proto @@ -0,0 +1,13 @@ +package reject.formats.colors; + +option NoBinary; + +/** Shared enums of a file without binary serialization. */ +enum Color { + RED; + GREEN; +} + +message Shade { + string name; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/graph/graph.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/graph/graph.proto new file mode 100644 index 00000000..e48be389 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/graph/graph.proto @@ -0,0 +1,10 @@ +package reject.formats.graph; +import "../colors/colors.proto"; + +option SharedGraph; + +/** A shared graph can use the enum, but not the message, of a file without SharedGraph. */ +message Node { + reject.formats.colors.Color color; + reject.formats.colors.Shade shade; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint-nobinary.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint-nobinary.proto new file mode 100644 index 00000000..2b1e606d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint-nobinary.proto @@ -0,0 +1,10 @@ +package reject.formats.paint; +import "../colors/colors.proto"; + +option NoBinary; + +/** Uses the enum and message of a NoBinary file without binary serialization itself. */ +message PaintNoBinary { + reject.formats.colors.Color color; + reject.formats.colors.Shade shade; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint.proto new file mode 100644 index 00000000..8675b337 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/formats/paint/paint.proto @@ -0,0 +1,14 @@ +package reject.formats.paint; +import "../colors/colors.proto"; + +/** Uses the enum of a NoBinary file, but generates binary serialization itself. */ +message Paint { + message Layer { + repeated reject.formats.colors.Color colors; + } + reject.formats.colors.Color color; + map shades; + + /** Not serialized in binary format, not a problem. */ + transient reject.formats.colors.Shade cached; +} From 05ca6ca5e1700901cb14da24436cc712dbb8579c Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 16:27:00 +0200 Subject: [PATCH 06/20] Stop writing transient and derived fields in XML format. The XML plugin wrote and read every field, while JSON and binary skip transient and derived fields. Transient values ended up in XML documents (#29, a bug by the maintainer's decision). For `@Container`, a contained object wrote its container, which wrote the object again, until the stack overflowed, so XML never worked for containment. The plugin now uses the same filter as the other formats in its writers, readers and field name constants. Readers of the default branches skip the attributes and elements of such fields in documents of earlier versions. `addFieldFormats()` follows, so a transient reference to a message of a NoXml file is accepted. Closes #29 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ README.md | 9 ++-- .../generator/plugins/XmlStreamingPlugin.java | 32 ++++++++++++- .../java/test/container/TestContainer.java | 27 +++++++++++ .../container/model/impl/MyContent_Impl.java | 13 +---- .../nointerfaces/model/MyContent.java | 13 +---- .../test/references/data/impl/A_Impl.java | 46 ------------------ .../test/references/data/impl/B_Impl.java | 47 +------------------ .../transientprops/TestTransientProps.java | 41 ++++++++++++++++ .../test/transientprops/data/impl/A_Impl.java | 12 ----- .../test/transientprops/data/impl/B_Impl.java | 12 ----- .../test/transientprops/data/impl/C_Impl.java | 12 ----- 12 files changed, 111 insertions(+), 157 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d8e08c4..331b4c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,10 @@ before, because enums always had all methods. It is now rejected with an error naming both files and the option, as are references to messages of such files and mixed `option SharedGraph` references, which generated uncompilable code before. The generator (CLI and Maven plugin) now stops without writing code when it finds such errors. +- **XML format: transient and derived fields** (#29): `transient` fields are no longer written in XML format, like in + JSON and binary format. **Wire format change:** XML documents no longer contain these attributes and elements; + readers ignore them in documents of earlier versions. The same applies to derived references (`@Container`, + `@Reverse`): writing an object whose container was set to XML recursed endlessly (`StackOverflowError`). ## 1.2.1 diff --git a/README.md b/README.md index 30daccc2..49648620 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,8 @@ message SearchResponse { ### Transient fields -Fields marked with `transient` are not serialized. They exist only in the in-memory representation: +Fields marked with `transient` are not serialized in any format (JSON, binary, XML). They exist only in the in-memory +representation. Readers ignore values of transient fields, e.g. in XML documents written by versions before 1.2.3: ```protobuf message A { @@ -210,7 +211,8 @@ other file. The generator rejects a reference to a definition generated without in that case. Either disable the format in the referencing file as well, or enable it in the referenced one. The same holds for `option SharedGraph`, which has its own JSON methods for messages: a message can reference messages of another file only if both files use `option SharedGraph`, or neither does. Enums are not affected by -`option SharedGraph`. `transient` fields are not written in JSON or binary format, so they don't need these formats. +`option SharedGraph`. `transient` fields and derived references (`@Container`, `@Reverse`) are not serialized, so they +don't need these formats. ### `option NoXmlNames` Disables generation of constants for the XML format. @@ -383,7 +385,8 @@ Sets a custom tag name for XML serialization. Marks a reference to be the reverse end of the reference with the given name in the target type. ### `@Container` -Marks a reference point to the container of the current object. +Marks a reference point to the container of the current object. The container reference is derived from the +containment and not serialized. ### `@Ref` Marks a reference as cross reference (non-composition). When setting values to fields marked as cross reference, container properties are not updated. diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index 0a2d1068..a40b0999 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -56,12 +56,25 @@ public void addFormats(Map options, Set formats) { @Override public void addFieldFormats(Map options, Field field, Set formats) { - // All fields except maps are written and read, including transient ones. - if (!noXml(options) && field.getType().kind() != Type.TypeKind.MAP_TYPE) { + // Maps are not supported in XML. + if (!noXml(options) && xmlSerialized(field) && field.getType().kind() != Type.TypeKind.MAP_TYPE) { formats.add(XML_FORMAT); } } + /** + * Whether the given field is written and read in XML format. + * + *

+ * Like in JSON and binary format, transient and derived fields (container and reverse + * references) are not serialized. Readers skip such attributes and elements in documents of + * earlier versions. + *

+ */ + static boolean xmlSerialized(Field field) { + return !field.isTransient() && !field.isDerived(); + } + @Override public void addInterfaces(Map options, MessageDef def, List generalizations) { if (noXml(options)) { @@ -108,6 +121,9 @@ protected void generate() { line("public static final String " + xmlTypeNameConstant(def) + " = \"" + xmlTypeName(def) + "\";"); for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } nl(); line("/** XML attribute or element name of a {@link #" + getterName(field) + "} property. */"); line("private static final String " + xmlFieldNameConstant(field) + " = \"" + xmlFieldName(field) + "\";"); @@ -145,6 +161,9 @@ protected void generate() { line("super.writeAttributes(out);"); } for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { line("out.writeAttribute(" + xmlFieldNameConstant(field) + ", " + asString(field, CodeConvention.getterName(field) + "()") + ");"); } @@ -165,6 +184,9 @@ protected void generate() { boolean hasElementFields = false; for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } Type type = field.getType(); switch (type.kind()) { case PRIMITIVE_TYPE: { @@ -290,6 +312,9 @@ protected void generate() { line("switch (name) {"); { for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { line("case " + xmlFieldNameConstant(field) + ": {"); { @@ -328,6 +353,9 @@ protected void generate() { { Set names = new HashSet<>(); for (Field field : def.getFields()) { + if (!xmlSerialized(field)) { + continue; + } if (!names.add(xmlFieldName(field))) { System.err.println("ERROR: Ambiguous element name '" + xmlFieldName(field) + "' in type '" + def.getName() + "'."); continue; diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/container/TestContainer.java b/de.haumacher.msgbuf.generator/src/test/java/test/container/TestContainer.java index b2b122b1..aecac4b4 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/container/TestContainer.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/container/TestContainer.java @@ -3,9 +3,15 @@ */ package test.container; +import java.io.StringReader; +import java.io.StringWriter; import java.util.Arrays; import java.util.Collections; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; + import junit.framework.TestCase; import test.container.model.MyContainer; import test.container.model.MyContent; @@ -189,4 +195,25 @@ public void testUpdateRef() { assertEquals(container, c.getContainer()); } + /** + * The container reference is derived and not written in XML format. Writing it made XML + * serialization recurse endlessly (issue #29). + */ + public void testXml() throws XMLStreamException { + MyContainer container = MyContainer.create().setName("c"); + container.setContent1(MyContent.create().setName("x")); + container.addContentList(MyContent.create().setName("y")); + + StringWriter buffer = new StringWriter(); + container.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + String xml = buffer.toString(); + assertEquals("" + + "", xml); + + MyContainer copy = MyContainer.readMyContainer(XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml))); + assertEquals("x", copy.getContent1().getName()); + assertSame(copy, copy.getContent1().getContainer()); + assertSame(copy, copy.getContentList().get(0).getContainer()); + } + } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/container/model/impl/MyContent_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/container/model/impl/MyContent_Impl.java index b0fc6d0e..da7ba8e0 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/container/model/impl/MyContent_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/container/model/impl/MyContent_Impl.java @@ -198,9 +198,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML element name representing a {@link test.container.model.MyContent} type. */ public static final String MY_CONTENT__XML_ELEMENT = "my-content"; - /** XML attribute or element name of a {@link #getContainer} property. */ - private static final String CONTAINER__XML_ATTR = "container"; - /** XML attribute or element name of a {@link #getName} property. */ private static final String NAME__XML_ATTR = "name"; @@ -222,11 +219,7 @@ protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws java /** Serializes all fields that are written as XML elements. */ protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { - if (hasContainer()) { - out.writeStartElement(CONTAINER__XML_ATTR); - getContainer().writeContent(out); - out.writeEndElement(); - } + // No element fields. } /** Creates a new {@link test.container.model.MyContent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ @@ -272,10 +265,6 @@ protected void readFieldXmlAttribute(String name, String value) { /** Reads the element under the cursor and assigns its contents to the field with the given name. */ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { switch (localName) { - case CONTAINER__XML_ATTR: { - setContainer(test.container.model.impl.MyContainer_Impl.readMyContainer_XmlContent(in)); - break; - } case NAME__XML_ATTR: { setName(in.getElementText()); break; diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/container/nointerfaces/model/MyContent.java b/de.haumacher.msgbuf.generator/src/test/java/test/container/nointerfaces/model/MyContent.java index df8cbdb3..87dbce0e 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/container/nointerfaces/model/MyContent.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/container/nointerfaces/model/MyContent.java @@ -231,9 +231,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML element name representing a {@link test.container.nointerfaces.model.MyContent} type. */ public static final String MY_CONTENT__XML_ELEMENT = "my-content"; - /** XML attribute or element name of a {@link #getContainer} property. */ - private static final String CONTAINER__XML_ATTR = "container"; - /** XML attribute or element name of a {@link #getName} property. */ private static final String NAME__XML_ATTR = "name"; @@ -255,11 +252,7 @@ protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws java /** Serializes all fields that are written as XML elements. */ protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { - if (hasContainer()) { - out.writeStartElement(CONTAINER__XML_ATTR); - getContainer().writeContent(out); - out.writeEndElement(); - } + // No element fields. } /** Creates a new {@link test.container.nointerfaces.model.MyContent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ @@ -305,10 +298,6 @@ protected void readFieldXmlAttribute(String name, String value) { /** Reads the element under the cursor and assigns its contents to the field with the given name. */ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { switch (localName) { - case CONTAINER__XML_ATTR: { - setContainer(test.container.nointerfaces.model.MyContainer.readMyContainer_XmlContent(in)); - break; - } case NAME__XML_ATTR: { setName(in.getElementText()); break; diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/A_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/A_Impl.java index 8a76a6df..34762e70 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/A_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/A_Impl.java @@ -692,12 +692,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML attribute or element name of a {@link #getOthers} property. */ private static final String OTHERS__XML_ATTR = "others"; - /** XML attribute or element name of a {@link #getInOther} property. */ - private static final String IN_OTHER__XML_ATTR = "in-other"; - - /** XML attribute or element name of a {@link #getInOthers} property. */ - private static final String IN_OTHERS__XML_ATTR = "in-others"; - @Override public String getXmlTagName() { return A__XML_ELEMENT; @@ -746,16 +740,6 @@ protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax. element.writeTo(out); } out.writeEndElement(); - out.writeStartElement(IN_OTHER__XML_ATTR); - for (test.references.data.A element : getInOther()) { - element.writeTo(out); - } - out.writeEndElement(); - out.writeStartElement(IN_OTHERS__XML_ATTR); - for (test.references.data.A element : getInOthers()) { - element.writeTo(out); - } - out.writeEndElement(); } /** Creates a new {@link test.references.data.A} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ @@ -829,14 +813,6 @@ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String l internalReadOthersListXml(in); break; } - case IN_OTHER__XML_ATTR: { - internalReadInOtherListXml(in); - break; - } - case IN_OTHERS__XML_ATTR: { - internalReadInOthersListXml(in); - break; - } default: { internalSkipUntilMatchingEndElement(in); } @@ -886,26 +862,4 @@ private void internalReadOthersListXml(javax.xml.stream.XMLStreamReader in) thro } } - private void internalReadInOtherListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { - while (true) { - int event = in.nextTag(); - if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { - break; - } - - addInOther(test.references.data.impl.A_Impl.readA_XmlContent(in)); - } - } - - private void internalReadInOthersListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { - while (true) { - int event = in.nextTag(); - if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { - break; - } - - addInOthers(test.references.data.impl.A_Impl.readA_XmlContent(in)); - } - } - } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/B_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/B_Impl.java index f196d9fd..aedc5913 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/B_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/references/data/impl/B_Impl.java @@ -275,12 +275,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML attribute or element name of a {@link #getName} property. */ private static final String NAME__XML_ATTR = "name"; - /** XML attribute or element name of a {@link #getInBs} property. */ - private static final String IN_BS__XML_ATTR = "in-bs"; - - /** XML attribute or element name of a {@link #getInB} property. */ - private static final String IN_B__XML_ATTR = "in-b"; - @Override public String getXmlTagName() { return B__XML_ELEMENT; @@ -299,16 +293,7 @@ protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws java /** Serializes all fields that are written as XML elements. */ protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { - out.writeStartElement(IN_BS__XML_ATTR); - for (test.references.data.A element : getInBs()) { - element.writeTo(out); - } - out.writeEndElement(); - out.writeStartElement(IN_B__XML_ATTR); - for (test.references.data.A element : getInB()) { - element.writeTo(out); - } - out.writeEndElement(); + // No element fields. } /** Creates a new {@link test.references.data.B} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ @@ -358,14 +343,6 @@ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String l setName(in.getElementText()); break; } - case IN_BS__XML_ATTR: { - internalReadInBsListXml(in); - break; - } - case IN_B__XML_ATTR: { - internalReadInBListXml(in); - break; - } default: { internalSkipUntilMatchingEndElement(in); } @@ -382,26 +359,4 @@ protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream } } - private void internalReadInBsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { - while (true) { - int event = in.nextTag(); - if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { - break; - } - - addInBs(test.references.data.impl.A_Impl.readA_XmlContent(in)); - } - } - - private void internalReadInBListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { - while (true) { - int event = in.nextTag(); - if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { - break; - } - - addInB(test.references.data.impl.A_Impl.readA_XmlContent(in)); - } - } - } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/TestTransientProps.java b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/TestTransientProps.java index 88284748..5f7465f3 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/TestTransientProps.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/TestTransientProps.java @@ -5,10 +5,16 @@ */ package test.transientprops; +import java.io.StringReader; +import java.io.StringWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; + import junit.framework.TestCase; import test.transientprops.data.A; import test.transientprops.data.B; @@ -34,6 +40,41 @@ public void testC() { assertEquals(Arrays.asList(A.X_1__PROP, A.X_2__PROP, B.Y_1__PROP, B.Y_2__PROP, C.Z_1__PROP, C.Z_2__PROP), C.create().properties()); } + /** Transient properties are not written in XML format (issue #29). */ + public void testXml() throws XMLStreamException { + C value = C.create().setX1("a").setX2("t").setY1("b").setY2("tt").setZ1("c").setZ2("ttt"); + String xml = xml(value); + assertEquals("", xml); + + C copy = C.readC(xmlReader(xml)); + assertEquals("a", copy.getX1()); + assertEquals("b", copy.getY1()); + assertEquals("c", copy.getZ1()); + assertEquals("", copy.getX2()); + assertEquals("", copy.getZ2()); + } + + /** Documents of earlier versions that contain transient properties can still be read. */ + public void testXmlReadLegacy() throws XMLStreamException { + C copy = C.readC(xmlReader("")); + assertEquals("a", copy.getX1()); + assertEquals("b", copy.getY1()); + assertEquals("c", copy.getZ1()); + assertEquals("", copy.getX2()); + assertEquals("", copy.getY2()); + assertEquals("", copy.getZ2()); + } + + private static String xml(C value) throws XMLStreamException { + StringWriter buffer = new StringWriter(); + value.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + return buffer.toString(); + } + + private static javax.xml.stream.XMLStreamReader xmlReader(String xml) throws XMLStreamException { + return XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)); + } + private Set set(String ...s) { return new HashSet<>(Arrays.asList(s)); } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/A_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/A_Impl.java index 00ec7a92..4f7d6797 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/A_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/A_Impl.java @@ -197,9 +197,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML attribute or element name of a {@link #getX1} property. */ private static final String X_1__XML_ATTR = "x-1"; - /** XML attribute or element name of a {@link #getX2} property. */ - private static final String X_2__XML_ATTR = "x-2"; - @Override public String getXmlTagName() { return A__XML_ELEMENT; @@ -214,7 +211,6 @@ public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws java /** Serializes all fields that are written as XML attributes. */ protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { out.writeAttribute(X_1__XML_ATTR, getX1()); - out.writeAttribute(X_2__XML_ATTR, getX2()); } /** Serializes all fields that are written as XML elements. */ @@ -256,10 +252,6 @@ protected void readFieldXmlAttribute(String name, String value) { setX1(value); break; } - case X_2__XML_ATTR: { - setX2(value); - break; - } default: { // Skip unknown attribute. } @@ -273,10 +265,6 @@ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String l setX1(in.getElementText()); break; } - case X_2__XML_ATTR: { - setX2(in.getElementText()); - break; - } default: { internalSkipUntilMatchingEndElement(in); } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/B_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/B_Impl.java index 89f9a5a8..313c5822 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/B_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/B_Impl.java @@ -169,9 +169,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML attribute or element name of a {@link #getY1} property. */ private static final String Y_1__XML_ATTR = "y-1"; - /** XML attribute or element name of a {@link #getY2} property. */ - private static final String Y_2__XML_ATTR = "y-2"; - @Override public String getXmlTagName() { return B__XML_ELEMENT; @@ -182,7 +179,6 @@ public String getXmlTagName() { protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { super.writeAttributes(out); out.writeAttribute(Y_1__XML_ATTR, getY1()); - out.writeAttribute(Y_2__XML_ATTR, getY2()); } /** Serializes all fields that are written as XML elements. */ @@ -206,10 +202,6 @@ protected void readFieldXmlAttribute(String name, String value) { setY1(value); break; } - case Y_2__XML_ATTR: { - setY2(value); - break; - } default: { super.readFieldXmlAttribute(name, value); } @@ -223,10 +215,6 @@ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String l setY1(in.getElementText()); break; } - case Y_2__XML_ATTR: { - setY2(in.getElementText()); - break; - } default: { super.readFieldXmlElement(in, localName); } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/C_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/C_Impl.java index bc857802..281119c5 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/C_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/transientprops/data/impl/C_Impl.java @@ -181,9 +181,6 @@ protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) th /** XML attribute or element name of a {@link #getZ1} property. */ private static final String Z_1__XML_ATTR = "z-1"; - /** XML attribute or element name of a {@link #getZ2} property. */ - private static final String Z_2__XML_ATTR = "z-2"; - @Override public String getXmlTagName() { return C__XML_ELEMENT; @@ -194,7 +191,6 @@ public String getXmlTagName() { protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { super.writeAttributes(out); out.writeAttribute(Z_1__XML_ATTR, getZ1()); - out.writeAttribute(Z_2__XML_ATTR, getZ2()); } /** Serializes all fields that are written as XML elements. */ @@ -218,10 +214,6 @@ protected void readFieldXmlAttribute(String name, String value) { setZ1(value); break; } - case Z_2__XML_ATTR: { - setZ2(value); - break; - } default: { super.readFieldXmlAttribute(name, value); } @@ -235,10 +227,6 @@ protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String l setZ1(in.getElementText()); break; } - case Z_2__XML_ATTR: { - setZ2(in.getElementText()); - break; - } default: { super.readFieldXmlElement(in, localName); } From f61ff0ed0e5923caa7415185fdb06aaa84780d44 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 16:30:07 +0200 Subject: [PATCH 07/20] Reject fields that redeclare inherited fields or clash in their generated names. A sub-message could redeclare a field of a generalization, e.g. to narrow its type. The generator accepted it silently and produced Java that did not compile: two getters with incompatible return types and ambiguous property constants (#21). As decided by the maintainer, redeclaration is not supported. It is rejected before any code is written, like the format references of #20, with an error that names the field and the message and file declaring the other one. The check compares the generated names (accessor suffix and property constant), so it also covers duplicate fields in one message and different names that generate the same Java names, like `foo_bar` and `fooBar`. It follows `extends` across files and guards against cycles. The rejection tests move to `test.validation`. Closes #21 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + README.md | 5 + .../haumacher/msgbuf/generator/Generator.java | 97 +++++++++++++++++++ .../java/test/validation/TestFieldNames.java | 75 ++++++++++++++ .../TestFormatReferences.java | 2 +- .../test/resources/reject/fields/base.proto | 7 ++ .../resources/reject/fields/extension.proto | 6 ++ .../resources/reject/fields/hierarchy.proto | 37 +++++++ .../resources/reject/fields/redeclare.proto | 9 ++ 9 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFieldNames.java rename de.haumacher.msgbuf.generator/src/test/java/test/{enumoptions => validation}/TestFormatReferences.java (99%) create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/fields/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/fields/extension.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/fields/hierarchy.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/fields/redeclare.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 331b4c61..f9354651 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,9 @@ JSON and binary format. **Wire format change:** XML documents no longer contain these attributes and elements; readers ignore them in documents of earlier versions. The same applies to derived references (`@Container`, `@Reverse`): writing an object whose container was set to XML recursed endlessly (`StackOverflowError`). +- **Redeclared fields** (#21): A field that redeclares an inherited field (directly or through any generalization, + also across files), a field declared twice, and fields whose names generate the same Java names (e.g. `foo_bar` and + `fooBar`) are rejected with an error. Before, the generator silently produced Java code that did not compile. ## 1.2.1 diff --git a/README.md b/README.md index 49648620..7f044439 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,11 @@ message Group extends Shape { Passing these definitions to the `msgbuf` compiler gives you a class hierarchy with classes `Shape`, `Circle`, `Rectangle`, and `Group`. You can inspect the generation result in the test package [test.hierarchy](https://github.com/msgbuf/msgbuf/tree/main/de.haumacher.msgbuf.generator/src/test/java/test/hierarchy/data) of the compiler. The source of the example data class definitions can be seen in the [hierarchy.proto](https://github.com/msgbuf/msgbuf/tree/main/de.haumacher.msgbuf.generator/src/test/java/test/hierarchy/data/hierarchy.proto) file. +A sub-message inherits all fields of its generalizations and cannot redeclare them, not even to narrow the type. The +names of all fields of a message, including the inherited ones, must also generate distinct Java names: `foo_bar` +and `fooBar` both generate `getFooBar()`. The generator rejects such definitions with an error naming the field and +the message declaring the other one. + ### Enum types Enums define a fixed set of named constants. Each constant is terminated with a semicolon. Constants can optionally diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 38565465..25ca5868 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -14,6 +14,7 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -186,6 +187,7 @@ public void generate(GeneratorPlugin plugin) { List errors = new ArrayList<>(); for (DefinitionFile file : _files) { if (!_importedFiles.contains(file)) { + validateFieldNames(file, errors); validateFormatReferences(file, plugin, errors); } } @@ -348,6 +350,101 @@ private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, List + * A sub-message cannot redeclare an inherited field (not even to narrow its type), since the + * generated accessors and property constants of both declarations would clash. + *

+ */ + private void validateFieldNames(DefinitionFile file, List errors) { + for (Definition def : file.getDefinitions()) { + validateFieldNames(def, errors); + } + } + + private void validateFieldNames(Definition def, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + + // Generated names of the inherited fields, most general first. + Map inherited = new HashMap<>(); + Map owners = new HashMap<>(); + List generalizations = new ArrayList<>(); + Set seen = new HashSet<>(); + seen.add(message); + for (MessageDef current = message.getExtendedDef(); current != null && seen.add(current); current = current.getExtendedDef()) { + generalizations.add(0, current); + } + for (MessageDef generalization : generalizations) { + for (Field field : generalization.getFields()) { + owners.put(field, generalization); + for (String name : generatedNames(field)) { + inherited.putIfAbsent(name, field); + } + } + } + + Map local = new HashMap<>(); + for (Field field : message.getFields()) { + Field clash = null; + for (String name : generatedNames(field)) { + clash = local.get(name); + if (clash != null) { + break; + } + } + if (clash != null) { + errors.add(fieldError(message, field) + (clash.getName().equals(field.getName()) + ? " is declared twice. Rename or remove one of the declarations." + : " clashes with field '" + clash.getName() + "' of the same message: both generate the same Java names ('" + + CodeConvention.getterName(field) + "()', '" + CodeConvention.constant(field) + + "'). Rename one of the fields.")); + } else { + for (String name : generatedNames(field)) { + clash = inherited.get(name); + if (clash != null) { + break; + } + } + if (clash != null) { + MessageDef owner = owners.get(clash); + String origin = "'" + Util.toString(owner) + "' of '" + sourceDescription(Util.definingFile(owner)) + "'"; + errors.add(fieldError(message, field) + (clash.getName().equals(field.getName()) + ? " redeclares the field inherited from " + origin + + ". A sub-message cannot redeclare an inherited field (not even to narrow its type)." + + " Remove the declaration or rename the field." + : " clashes with field '" + clash.getName() + "' inherited from " + origin + + ": both generate the same Java names ('" + CodeConvention.getterName(field) + "()', '" + + CodeConvention.constant(field) + "'). Rename the field.")); + } + } + for (String name : generatedNames(field)) { + local.putIfAbsent(name, field); + } + } + + for (Definition inner : message.getDefinitions()) { + validateFieldNames(inner, errors); + } + } + + private String fieldError(MessageDef message, Field field) { + return sourceDescription(Util.definingFile(message)) + ": Field '" + Util.toString(message) + "." + field.getName() + "'"; + } + + /** + * The names derived from a field that must be unique among all fields of a message and its + * generalizations. + */ + private static List generatedNames(Field field) { + return Arrays.asList("suffix:" + CodeConvention.suffix(field), "constant:" + CodeConvention.constant(field)); + } + /** * Rejects references to definitions of other files that are generated without a serialization * format that the referencing code needs. diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFieldNames.java b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFieldNames.java new file mode 100644 index 00000000..a5da8a35 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFieldNames.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.validation; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +import de.haumacher.msgbuf.generator.Generator; +import de.haumacher.msgbuf.generator.GeneratorException; +import de.haumacher.msgbuf.generator.parser.ParseException; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; +import junit.framework.TestCase; + +/** + * Test case for rejecting fields that redeclare inherited fields or whose generated names clash + * (issue #21). + */ +@SuppressWarnings("javadoc") +public class TestFieldNames extends TestCase { + + private static final File FIXTURES = new File("src/test/resources/reject/fields"); + + /** The definition from the issue report. */ + public void testRedeclare() throws IOException, ParseException { + assertEquals(Arrays.asList( + "test/redeclare/redeclare.proto: Field 'test.redeclare.B.value' redeclares the field inherited from" + + " 'test.redeclare.A' of 'test/redeclare/redeclare.proto'. A sub-message cannot redeclare an inherited" + + " field (not even to narrow its type). Remove the declaration or rename the field."), + reject("redeclare.proto")); + } + + public void testHierarchy() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/fields/hierarchy.proto: Field 'reject.fields.Outer.label' is declared twice. Rename or remove one of" + + " the declarations.", + "reject/fields/hierarchy.proto: Field 'reject.fields.Outer.Leaf.name' redeclares the field inherited from" + + " 'reject.fields.Root' of 'reject/fields/hierarchy.proto'. A sub-message cannot redeclare an inherited" + + " field (not even to narrow its type). Remove the declaration or rename the field.", + "reject/fields/hierarchy.proto: Field 'reject.fields.Outer.Other.foo_bar' clashes with field 'fooBar'" + + " inherited from 'reject.fields.Root' of 'reject/fields/hierarchy.proto': both generate the same Java" + + " names ('getFooBar()', 'FOO_BAR__PROP'). Rename the field."), + reject("hierarchy.proto")); + } + + public void testCrossFile() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/fields/ext/extension.proto: Field 'reject.fields.ext.Ping.source' redeclares the field inherited" + + " from 'reject.fields.Event' of 'reject/fields/base.proto'. A sub-message cannot redeclare an" + + " inherited field (not even to narrow its type). Remove the declaration or rename the field."), + reject("extension.proto")); + } + + private List reject(String proto) throws IOException, ParseException { + File target = new File("target"); + target.mkdirs(); + File out = Files.createTempDirectory(target.toPath(), getName()).toFile(); + Generator generator = new Generator(); + generator.setOut(out); + generator.load(new File(FIXTURES, proto)); + try { + generator.generate(new XmlStreamingPlugin()); + fail("Expected rejection of '" + proto + "'."); + return null; + } catch (GeneratorException ex) { + String[] written = out.list(); + assertTrue("No code must be generated for rejected definitions.", written == null || written.length == 0); + return ex.getErrors(); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFormatReferences.java similarity index 99% rename from de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java rename to de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFormatReferences.java index a79b9e01..4d2ef7bb 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/enumoptions/TestFormatReferences.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestFormatReferences.java @@ -1,7 +1,7 @@ /* * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. */ -package test.enumoptions; +package test.validation; import java.io.File; import java.io.IOException; diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/base.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/base.proto new file mode 100644 index 00000000..6f337e39 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/base.proto @@ -0,0 +1,7 @@ +package reject.fields; + +option OpenWorld; + +abstract message Event { + string source; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/extension.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/extension.proto new file mode 100644 index 00000000..e00914cd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/extension.proto @@ -0,0 +1,6 @@ +package reject.fields.ext; +import "base.proto"; + +message Ping extends reject.fields.Event { + string source; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/hierarchy.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/hierarchy.proto new file mode 100644 index 00000000..1b52d966 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/hierarchy.proto @@ -0,0 +1,37 @@ +package reject.fields; + +/** Redeclarations through an abstract intermediate, in nested messages, and clashing generated names. */ +abstract message Root { + string name; + int fooBar; +} + +abstract message Middle extends Root { + int weight; +} + +message Outer { + message Leaf extends Middle { + string name; + } + + message Other extends Root { + string foo_bar; + } + + string label; + int label; +} + +/** Siblings may declare the same field, and nested messages may reuse names of their outer message. */ +message Sibling1 extends Middle { + string extra; +} + +message Sibling2 extends Middle { + int extra; + + message Inner { + int extra; + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/redeclare.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/redeclare.proto new file mode 100644 index 00000000..f569042f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/fields/redeclare.proto @@ -0,0 +1,9 @@ +package test.redeclare; + +message A { + json value; +} + +message B extends A { + string value; +} From 73fa1e8e988006bba7f4dda1f72f817ff0a7b56e Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 16:34:38 +0200 Subject: [PATCH 08/20] Accept the documented names of the Maven plugin parameters and make the plugin IT real. The Mojo fields are named `_outputDirectory`, `_input`, `_includePaths` and `_resourceOutputDirectory`, and Maven uses the field name as the configuration name unless an alias is declared. Only the user properties worked, and the README's `` was silently ignored (#17). The parameters now have aliases with their natural names, like `typeScriptOutputDirectory` already had, and the README lists all parameters. The integration test was the archetype template calling a non-existent `touch` goal (#18). It is now a consumer project that configures every parameter by its documented name, resolves an import through `includePaths`, generates an OpenWorld extension with its service descriptor, and compiles the result. The plugin testing harness does not resolve aliases, so the names can only be tested there. The IT fails when one alias is removed. Closes #17 Closes #18 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++ README.md | 17 ++++++- .../src/it/simple-it/pom.xml | 48 +++++++++++++++++-- .../simple-it/src/main/proto/base/base.proto | 7 +++ .../it/simple-it/src/main/proto/ext/ext.proto | 6 +++ .../src/it/simple-it/verify.groovy | 18 ++++++- .../maven/GenerateMessageClasses.java | 8 ++-- 7 files changed, 98 insertions(+), 11 deletions(-) create mode 100644 msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/base/base.proto create mode 100644 msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/ext/ext.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 236509e0..77fff8dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ - **File documentation comment**: A doc comment before the `syntax` or `package` declaration is kept as the documentation of the `.proto` file (`DefinitionFile.comment`) and emitted as TSDoc `@packageDocumentation` of the TypeScript module. +### Bug Fixes +- **Maven plugin parameter names** (#17): The parameters `input`, `outputDirectory`, `resourceOutputDirectory` and + `includePaths` can be set under these names in the plugin ``. Before, only the user properties + (`-DoutputDir=…`) worked, and the README's `` was silently ignored. + ## 1.2.1 ### Bug Fixes diff --git a/README.md b/README.md index fe703035..c57c7dd1 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,21 @@ Now you are ready to create `*.proto` files in your source folder and build them Proto files are placed in your Java source folder (`src/main/java/`) inside the directory matching their `package` declaration. The generated Java files are written next to the proto file. For example, a proto file with `package my.app.model;` should be placed at `src/main/java/my/app/model/shape.proto`, and the generated classes will appear in `src/main/java/my/app/model/`. +### Plugin parameters + +All parameters are optional. Set them in the `` of the plugin (or its execution), or with the user +property on the command line (`-D=...`): + +| Parameter | User property | Default | Description | +|---|---|---|---| +| `input` | `input` | `${project.build.sourceDirectory}` | Directory searched for `.proto` files (or a single `.proto` file). | +| `outputDirectory` | `outputDir` | `${project.build.sourceDirectory}` | Directory the Java sources are generated to. | +| `resourceOutputDirectory` | `resourceOutputDir` | `${project.basedir}/src/main/resources` | Directory resource files (`META-INF/services`) are generated to. | +| `typeScriptOutputDirectory` | `typeScriptOutputDir` | none | Directory TypeScript types are generated to (see [TypeScript](#typescript-type-definitions)). | +| `includePaths` | `includePaths` | none | Additional directories searched for imported `.proto` files. | + +If `outputDirectory` is not a source folder of the project, add it as one (e.g. with the `build-helper-maven-plugin`). + ## Usage The `msgbuf` definition language is an extension of the [proto format](https://developers.google.com/protocol-buffers/docs/proto3) from `protobuf`. A defined message can `extend` another message type, or it can be marked `abstract`. @@ -291,7 +306,7 @@ Implications: Maven plugin configuration (extension module): ```xml - ${project.basedir}/src/main/resources + ${project.basedir}/src/main/resources ``` diff --git a/msgbuf-generator-maven-plugin/src/it/simple-it/pom.xml b/msgbuf-generator-maven-plugin/src/it/simple-it/pom.xml index 4e81df15..b257e6ac 100644 --- a/msgbuf-generator-maven-plugin/src/it/simple-it/pom.xml +++ b/msgbuf-generator-maven-plugin/src/it/simple-it/pom.xml @@ -7,12 +7,25 @@ simple-it 1.0-SNAPSHOT - A simple IT verifying the basic use case. + + Generates and compiles data classes in a consumer project, configuring the plugin with the parameter names + documented in the README. + UTF-8 + 11 + 11 + + + de.haumacher.msgbuf + msgbuf-api + @project.version@ + + + @@ -21,11 +34,38 @@ @project.version@ - touch - validate - touch + generate + + + ${project.basedir}/src/main/proto + + ${project.basedir}/src/main/proto + + ${project.build.directory}/generated-sources/msgbuf + ${project.build.directory}/generated-resources/msgbuf + ${project.build.directory}/generated-ts + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-generated-sources + generate-sources + + add-source + + + ${project.build.directory}/generated-sources/msgbuf + + diff --git a/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/base/base.proto b/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/base/base.proto new file mode 100644 index 00000000..edf5aee1 --- /dev/null +++ b/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/base/base.proto @@ -0,0 +1,7 @@ +package it.base; + +option OpenWorld; + +abstract message Event { + string source; +} diff --git a/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/ext/ext.proto b/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/ext/ext.proto new file mode 100644 index 00000000..c595f0ab --- /dev/null +++ b/msgbuf-generator-maven-plugin/src/it/simple-it/src/main/proto/ext/ext.proto @@ -0,0 +1,6 @@ +package it.ext; +import "base/base.proto"; + +message Ping extends it.base.Event { + int count; +} diff --git a/msgbuf-generator-maven-plugin/src/it/simple-it/verify.groovy b/msgbuf-generator-maven-plugin/src/it/simple-it/verify.groovy index 7b307c78..05b591a1 100644 --- a/msgbuf-generator-maven-plugin/src/it/simple-it/verify.groovy +++ b/msgbuf-generator-maven-plugin/src/it/simple-it/verify.groovy @@ -1,3 +1,17 @@ -File touchFile = new File( basedir, "target/touch.txt" ); +// Generated to the configured directories (outputDirectory, resourceOutputDirectory, typeScriptOutputDirectory). +File java = new File(basedir, "target/generated-sources/msgbuf/it/ext/Ping.java") +assert java.isFile() : "Missing " + java -assert touchFile.isFile() +File services = new File(basedir, "target/generated-resources/msgbuf/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration") +assert services.isFile() : "Missing " + services +assert services.text.contains("it.ext.ExtTypes") + +File ts = new File(basedir, "target/generated-ts/it/ext/ext.ts") +assert ts.isFile() : "Missing " + ts + +// Nothing generated to the default locations. +assert !new File(basedir, "src/main/java").exists() +assert !new File(basedir, "src/main/resources").exists() + +// The generated sources were compiled. +assert new File(basedir, "target/classes/it/ext/impl/Ping_Impl.class").isFile() diff --git a/msgbuf-generator-maven-plugin/src/main/java/de/haumacher/msgbuf/generator/maven/GenerateMessageClasses.java b/msgbuf-generator-maven-plugin/src/main/java/de/haumacher/msgbuf/generator/maven/GenerateMessageClasses.java index 544bcf1e..6754ac8f 100644 --- a/msgbuf-generator-maven-plugin/src/main/java/de/haumacher/msgbuf/generator/maven/GenerateMessageClasses.java +++ b/msgbuf-generator-maven-plugin/src/main/java/de/haumacher/msgbuf/generator/maven/GenerateMessageClasses.java @@ -32,25 +32,25 @@ public class GenerateMessageClasses extends AbstractMojo { /** * Directory where to generate source code to. */ - @Parameter(defaultValue = "${project.build.sourceDirectory}", property = "outputDir", required = true) + @Parameter(alias = "outputDirectory", defaultValue = "${project.build.sourceDirectory}", property = "outputDir", required = true) private File _outputDirectory; /** * Input where to search for *.proto files. */ - @Parameter(defaultValue = "${project.build.sourceDirectory}", property = "input", required = true) + @Parameter(alias = "input", defaultValue = "${project.build.sourceDirectory}", property = "input", required = true) private File _input; /** * Additional directories to search for imported .proto files. */ - @Parameter(property = "includePaths") + @Parameter(alias = "includePaths", property = "includePaths") private List _includePaths; /** * Directory where to generate resource files (e.g. META-INF/services). */ - @Parameter(defaultValue = "${project.basedir}/src/main/resources", property = "resourceOutputDir") + @Parameter(alias = "resourceOutputDirectory", defaultValue = "${project.basedir}/src/main/resources", property = "resourceOutputDir") private File _resourceOutputDirectory; /** From a9a0f5e2199ebed5ba090ff14d87b8e709743f96 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 16:34:38 +0200 Subject: [PATCH 09/20] Remove the stale msgbuf-parent/ copy of the parent POM. msgbuf-parent/pom.xml was an outdated copy (1.0.3-SNAPSHOT) of the parent POM. The real parent is the root pom.xml. No module references it and the build never reads it, but it invited edits that have no effect (#19). Closes #19 Co-Authored-By: Claude Opus 5.5 --- msgbuf-parent/.gitignore | 1 - msgbuf-parent/.project | 17 -- .../.settings/org.eclipse.m2e.core.prefs | 4 - msgbuf-parent/pom.xml | 167 ------------------ 4 files changed, 189 deletions(-) delete mode 100644 msgbuf-parent/.gitignore delete mode 100644 msgbuf-parent/.project delete mode 100644 msgbuf-parent/.settings/org.eclipse.m2e.core.prefs delete mode 100644 msgbuf-parent/pom.xml diff --git a/msgbuf-parent/.gitignore b/msgbuf-parent/.gitignore deleted file mode 100644 index b83d2226..00000000 --- a/msgbuf-parent/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/msgbuf-parent/.project b/msgbuf-parent/.project deleted file mode 100644 index 892785de..00000000 --- a/msgbuf-parent/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - msgbuf-parent - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - diff --git a/msgbuf-parent/.settings/org.eclipse.m2e.core.prefs b/msgbuf-parent/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1..00000000 --- a/msgbuf-parent/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/msgbuf-parent/pom.xml b/msgbuf-parent/pom.xml deleted file mode 100644 index d655569d..00000000 --- a/msgbuf-parent/pom.xml +++ /dev/null @@ -1,167 +0,0 @@ - - 4.0.0 - - de.haumacher.msgbuf - msgbuf-parent - 1.0.3-SNAPSHOT - - pom - - - https://github.com/msgbuf/msgbuf - scm:git:https://github.com/msgbuf/msgbuf.git - scm:git:https://github.com/msgbuf/msgbuf.git - HEAD - - - - - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots - - - - - 11 - 11 - utf-8 - 3.3.9 - - - - - - - - maven-clean-plugin - 3.1.0 - - - maven-resources-plugin - 3.2.0 - - - maven-compiler-plugin - 3.10.1 - - - maven-plugin-plugin - 3.6.4 - - - maven-surefire-plugin - 2.22.1 - - - maven-jar-plugin - 3.0.2 - - - maven-install-plugin - 2.5.2 - - - maven-deploy-plugin - 2.8.2 - - - maven-invoker-plugin - 3.1.0 - - - - - - - - maven-compiler-plugin - - 11 - 11 - UTF-8 - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.3.1 - - UTF-8 - -missing - - - - attach-javadocs - - jar - - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - ${gpg.keyname} - - - - sign-artifacts - verify - - sign - - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - true - false - ossrh - deploy - msgbuf-api-@{project.version} - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://s01.oss.sonatype.org/ - false - - - - - \ No newline at end of file From 7091690ec907ac59542f03bc1ecab28b93cb7d4a Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 16:34:38 +0200 Subject: [PATCH 10/20] Document that the AST and the generated test sources are regenerated by hand. CLAUDE.md and the cross-file extension spec claimed that the Maven reactor regenerates the AST classes after a change to proto.proto. It does not: the generator pom only runs JavaCC and the shade plugin (#23). The docs now give the command (and the Eclipse launch configuration) for the AST and for the checked-in test sources. The workflow skill drops its notes on the fixed integration test (#18). A check that detects a forgotten regeneration, option 3 of #23, is left as an enhancement. Closes #23 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/msgbuf-workflow/SKILL.md | 12 ++++++------ CLAUDE.md | 2 +- ...026-03-24-cross-file-protocol-extension-design.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude/skills/msgbuf-workflow/SKILL.md b/.claude/skills/msgbuf-workflow/SKILL.md index fbe92bfd..b703c149 100644 --- a/.claude/skills/msgbuf-workflow/SKILL.md +++ b/.claude/skills/msgbuf-workflow/SKILL.md @@ -132,9 +132,10 @@ general?" not "does the happy path work?". Keep passing probes as permanent test is installed — use `-am`, and then `-Dsurefire.failIfNoSpecifiedTests=false` with `-Dtest=…`. - **Stale jar**: `target/msgbuf-generator-*-full.jar` is whatever the last `install`/`package` built, possibly on another branch. Rebuild before probing a change. -- **A green unit build does not cover the plugin integration test**: `-Prun-its` runs it, and - `simple-it` is the archetype template calling a non-existent `touch` goal (#18) — it fails on - `main` too. Report it as known, don't chase it. +- **A green unit build does not cover the plugin integration test**: `-Prun-its` runs `simple-it`, + a consumer project that configures the plugin with the documented parameter names, generates and + compiles. The plugin testing harness (`MojoRule.lookupConfiguredMojo`) does not resolve parameter + aliases, so configuration names can only be tested there. - **CLAUDE.md is not always right about the wire format**: polymorphic values are written as `[typeId, {fields}]` (a two-element array whose second element is the object), and only when the hierarchy root is abstract; references to a concrete type use `writeContent()` without a tag. @@ -175,7 +176,7 @@ cd .. && mvn clean install # the regenerated sources compile and pa generated code: an unexplained change is a regression. - **AST change** (`ast/proto.proto`): regenerate the AST classes with the previous generator (`java -jar $J -out src/main/java src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto`), - then rebuild. The build does not do this for you (#23; CLAUDE.md still claims otherwise). + then rebuild. The build does not do this for you. - **Grammar change** (`parser/protobuf.jj`, next to the parser sources): the JavaCC plugin regenerates the parser into `src/main/java` during the build; the regenerated parser files are checked in and ride the same commit. @@ -184,8 +185,7 @@ cd .. && mvn clean install # the regenerated sources compile and pa rerun without the flag. Type-check the golden files plus a usage file with `@ts-expect-error` negative cases in the scratchpad: `npx -y -p typescript tsc --strict --noEmit --isolatedModules --verbatimModuleSyntax --moduleResolution bundler --module esnext --target es2020 `. -- **Maven plugin changes**: also run `mvn install -Prun-its -pl msgbuf-generator-maven-plugin` - (known failure #18 until fixed). +- **Maven plugin changes**: also run `mvn install -Prun-its -pl msgbuf-generator-maven-plugin`. - The Eclipse plugin (`de.haumacher.msgbuf.eclipse`, `de.haumacher.msgbuf.feature`) is not in the reactor; changes there need a separate Eclipse/PDE build and are rare. diff --git a/CLAUDE.md b/CLAUDE.md index 6b2ade22..4600bed1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -83,7 +83,7 @@ Extensions beyond standard protobuf: ## Key Gotchas -- **Self-bootstrapping**: Changes to `generator/ast/proto.proto` require regenerating the AST Java classes with an existing generator, then rebuilding. Maven reactor handles this automatically. +- **Self-bootstrapping**: Changes to `generator/ast/proto.proto` require regenerating the AST Java classes with an existing generator, then rebuilding. The build does **not** do this: run `java -jar de.haumacher.msgbuf.generator/target/msgbuf-generator-*-full.jar -out de.haumacher.msgbuf.generator/src/main/java de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ast/proto.proto` (or the Eclipse launch config `de.haumacher.msgbuf.generator/bin/Generate Compiler AST.launch`). Likewise, the checked-in generated test sources under `src/test/java/test/**` are regenerated by hand (`-out src/test/java` for each `.proto`). - **NoInterfaces mode**: When set, generates single classes instead of interface + impl. Changes package structure (no `impl` subpackage). Many conditionals in `MessageGenerator` depend on this flag. - **Polymorphic JSON**: In a hierarchy with an abstract root, a value is written as a two-element array `[typeId, {fields}]` (the root's final `writeTo()`). A field declared with a concrete type of such a hierarchy uses `writeContent()` and writes the plain object without type info. A hierarchy with a concrete root carries no type info at all. - **Field IDs**: Auto-synthesis starts at 1, skips manually assigned IDs, is inheritance-aware (child fields can't clash with parent IDs). Field ID 0 is reserved. diff --git a/docs/superpowers/specs/2026-03-24-cross-file-protocol-extension-design.md b/docs/superpowers/specs/2026-03-24-cross-file-protocol-extension-design.md index b4079c9a..258cfb40 100644 --- a/docs/superpowers/specs/2026-03-24-cross-file-protocol-extension-design.md +++ b/docs/superpowers/specs/2026-03-24-cross-file-protocol-extension-design.md @@ -66,7 +66,7 @@ message DefinitionFile extends WithOptions { } ``` -**Bootstrapping note:** Since the generator is self-bootstrapping, this change requires: (1) add the field to `proto.proto`, (2) regenerate AST Java classes with the existing generator, (3) rebuild the generator. The Maven reactor handles this automatically. +**Bootstrapping note:** Since the generator is self-bootstrapping, this change requires: (1) add the field to `proto.proto`, (2) regenerate AST Java classes with the existing generator, (3) rebuild the generator. The build does not regenerate the AST classes; step (2) is a manual run of the generator (see CLAUDE.md, "Self-bootstrapping"). ### 4. Dynamic Type Registry From e5d3389a47f58b6ded4876c5075dcc326591dd59 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 17:24:04 +0200 Subject: [PATCH 11/20] Merge verified PRs as part of the msgbuf workflow. The skill ended the loop at "open the PR", so verified PRs piled up unmerged. The maintainer expects verified PRs to be merged by the session. The skill now says so, including the order for stacked PRs and the gate on a merged tree. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/msgbuf-workflow/SKILL.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.claude/skills/msgbuf-workflow/SKILL.md b/.claude/skills/msgbuf-workflow/SKILL.md index 2bf9964a..ebfb3529 100644 --- a/.claude/skills/msgbuf-workflow/SKILL.md +++ b/.claude/skills/msgbuf-workflow/SKILL.md @@ -34,8 +34,9 @@ Work is a pipeline, not a pile: 3. **Dispatch** one sub-agent per coherent package (§2), or do it yourself when the package is small. msgbuf has one toolchain and one reactor, so parallel work needs separate worktrees (§3). 4. **Review with a novel probe** (§4). Non-negotiable. -5. **Gate** (§5), **commit and open or update the PR** (§6), close the issue with the fixing - commit or PR plus a summary comment naming the regression test. +5. **Gate** (§5), **commit and open or update the PR** (§6), and **merge it** once review and gate + are green (§6). Close the issue with the fixing commit or PR plus a summary comment naming the + regression test. 6. **Before finishing: `gh issue list -R msgbuf/msgbuf`.** Anything you find and defer becomes an issue (like #16–#21, found while building the TypeScript target), so a crashed session loses nothing. @@ -208,6 +209,13 @@ check `git status` first. When reporting, give the numbers (tests per module) an description in the same step (§4 for the `gh` workaround). - **The agents don't commit; you do**, after review. Pushing and force-pushing a shared branch are the user's call; a history rewrite of a PR branch others may have checked out needs explicit consent. +- **Merge verified PRs yourself.** A PR that passed the probe review (§4) and the gate (§5) is + merged, not left open for the user. Use a merge commit, like the history (`gh api -X PUT + repos/msgbuf/msgbuf/pulls//merge -f merge_method=merge`; `gh pr merge` may hit the GraphQL error + of §4). Merge stacked PRs bottom-up, retargeting the next one to `main` first (`gh api -X PATCH + …/pulls/ -f base=main`), and delete a merged branch only after nothing is based on it. A PR that + conflicts with `main` gets `main` merged in, then the gate runs on that merged tree before it lands. + Stop at PRs that carry an open design question, and say so. - **Releases are the user's**: `mvn release:clean release:prepare` pushes a `msgbuf-api-` tag, and the tag push runs `.github/workflows/release.yml`, which deploys to Maven Central (HOWTO-RELEASE.md). Never run `release:*`, never push a `msgbuf-api-*` tag, never edit the From ed035be8d1f348424fa237e5e00331fd74ee6ac0 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 17:29:44 +0200 Subject: [PATCH 12/20] Require OpenWorld for extensions across files and support specializations nested in their generalization. Extending a message of another package without OpenWorld produced Java that did not compile (#25). Extending a message of an only imported file compiled in the same package, but the base's readers did not know the subtype. As decided by the maintainer, such inconsistent OpenWorld annotations are rejected. A message may extend a message of another file only if that file declares `option OpenWorld`; this includes intermediates in extension files. A closed hierarchy split into files of the same package that are generated together stays accepted, since it works. The check runs before the format and field name checks, which would otherwise report follow-up errors. It also rejects inheritance cycles, which crashed the generator. `FieldIDSynthesizer` computed the indexes of a message by visiting its generalization, and that visit descended into the nested definitions again, so a message nested in its own generalization recursed endlessly (#32). The indexes are now computed along the generalizations only and memoized. The assigned indexes are unchanged for all existing test protos. Closes #25 Closes #32 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + README.md | 8 +- .../msgbuf/generator/FieldIDSynthesizer.java | 36 +- .../haumacher/msgbuf/generator/Generator.java | 78 ++ .../java/test/nested/TestNestedRecursive.java | 82 ++ .../test/java/test/nested/recursive/Expr.java | 229 ++++++ .../test/java/test/nested/recursive/Node.java | 152 ++++ .../test/nested/recursive/impl/Expr_Impl.java | 777 ++++++++++++++++++ .../test/nested/recursive/impl/Node_Impl.java | 575 +++++++++++++ .../test/nested/recursive/recursive.proto | 28 + .../test/validation/TestGeneralizations.java | 101 +++ .../reject/openworld/base/closed.proto | 6 + .../reject/openworld/base/open.proto | 7 + .../reject/openworld/base/same-package.proto | 7 + .../resources/reject/openworld/cycle.proto | 9 + .../resources/reject/openworld/ext/leaf.proto | 6 + .../reject/openworld/ext/other-package.proto | 13 + .../resources/reject/openworld/mid/mid.proto | 7 + 18 files changed, 2123 insertions(+), 6 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedRecursive.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Expr.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Node.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Expr_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Node_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/recursive.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/validation/TestGeneralizations.java create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/closed.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/open.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/same-package.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/cycle.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/leaf.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/other-package.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/mid/mid.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f1eb809..2a1c5390 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,14 @@ - **Redeclared fields** (#21): A field that redeclares an inherited field (directly or through any generalization, also across files), a field declared twice, and fields whose names generate the same Java names (e.g. `foo_bar` and `fooBar`) are rejected with an error. Before, the generator silently produced Java code that did not compile. +- **Extensions across files require OpenWorld** (#25): A message that extends a message of another file is rejected + unless that file declares `option OpenWorld`. Extending from another package produced Java that did not compile. + **Source compatibility:** extending a message of an only imported (not generated together) file of the same package + compiled before, but the readers of the base did not know the subtype. It is now rejected as well. A closed + hierarchy split into files of the same package that are generated together is still accepted. Inheritance cycles + are rejected with an error instead of crashing the generator. +- **Nested specializations of the outer message** (#32): A message nested in its own generalization (e.g. + `abstract message Expr { message Sum extends Expr {…} }`) crashed the generator with a `StackOverflowError`. ## 1.2.1 diff --git a/README.md b/README.md index 21455245..d640f63b 100644 --- a/README.md +++ b/README.md @@ -279,7 +279,13 @@ message Config { ### `option OpenWorld` Enables cross-file protocol extension for abstract type hierarchies. With this option, subtypes can be defined in -separate `.proto` files (and separate modules) using `import` and `extends`: +separate `.proto` files (and separate modules) using `import` and `extends`. + +A message can extend a message of another file only if that file declares `option OpenWorld`, so that the readers of +the hierarchy resolve types of other files. This also holds for an intermediate: to extend a message of an extension +file, the extension file must declare `option OpenWorld` as well. The only exception is a hierarchy without +`OpenWorld` that is split into several files of the same package, which are generated together. The generator rejects +other extensions across files with an error. ```protobuf // base-module: events.proto diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java index 32dbd079..a23cacd3 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/FieldIDSynthesizer.java @@ -20,6 +20,11 @@ * assigned in the message definition. */ public class FieldIDSynthesizer implements Definition.Visitor, Void> { + + /** + * Names of all fields by index for each processed message, including inherited fields. + */ + private final Map> _indexes = new HashMap<>(); /** * Assigns IDs in the given file. @@ -65,9 +70,33 @@ private void error(String message) { @Override public Map visit(MessageDef self, Void arg) { + Map result = indexes(self); + for (Definition inner : self.getDefinitions()) { + inner.visit(this, arg); + } + return result; + } + + /** + * Assigns the field indexes of the given message (and its generalizations) and returns the + * names of all its fields, including the inherited ones, by index. + * + *

+ * Walks the generalizations only, not the nested definitions: a nested message may extend its + * outer message. + *

+ */ + private Map indexes(MessageDef self) { + Map cached = _indexes.get(self); + if (cached != null) { + return cached; + } + // Guards against an inheritance cycle, which the generator rejects before. + _indexes.put(self, new HashMap<>()); + Map partByIndex; if (self.getExtendedDef() != null) { - partByIndex = self.getExtendedDef().visit(this, arg); + partByIndex = new HashMap<>(indexes(self.getExtendedDef())); } else { partByIndex = new HashMap<>(); } @@ -94,11 +123,8 @@ public Map visit(MessageDef self, Void arg) { field.setIndex(nextIndex); } } - - for (Definition inner : self.getDefinitions()) { - inner.visit(this, arg); - } + _indexes.put(self, partByIndex); return partByIndex; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 25ca5868..6dcbce44 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -185,6 +185,15 @@ public void generate(GeneratorPlugin plugin) { } List errors = new ArrayList<>(); + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file)) { + validateGeneralizations(file, errors); + } + } + if (!errors.isEmpty()) { + // Checks below depend on a consistent hierarchy. + throw new GeneratorException(errors); + } for (DefinitionFile file : _files) { if (!_importedFiles.contains(file)) { validateFieldNames(file, errors); @@ -350,6 +359,75 @@ private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, Listoption OpenWorld. + * + *

+ * The readers of a hierarchy must know all its types. A message of another file can therefore + * only be extended if that file declares option OpenWorld, which makes its readers + * resolve extension types through a registry. The only exception is a closed hierarchy that is + * split into several files of the same package and generated together: then the readers of the + * extended message are generated with all its specializations. + *

+ */ + private void validateGeneralizations(DefinitionFile file, List errors) { + for (Definition def : file.getDefinitions()) { + validateGeneralizations(file, def, errors); + } + } + + private void validateGeneralizations(DefinitionFile file, Definition def, List errors) { + if (!(def instanceof MessageDef)) { + return; + } + MessageDef message = (MessageDef) def; + MessageDef extended = message.getExtendedDef(); + if (extended != null) { + List path = new ArrayList<>(); + path.add(message); + for (MessageDef current = extended; current != null; current = current.getExtendedDef()) { + if (current == message) { + path.add(current); + errors.add(sourceDescription(file) + ": Message '" + Util.toString(message) + + "' is part of an inheritance cycle: " + + path.stream().map(Util::toString).collect(java.util.stream.Collectors.joining(" extends ")) + + ". Remove one of the extends clauses."); + break; + } + if (path.contains(current)) { + // A cycle not containing this message, reported for its members. + break; + } + path.add(current); + } + + DefinitionFile extendedFile = Util.definingFile(extended); + if (extendedFile != file && !Util.getFlag(extendedFile, "OpenWorld") + && !(samePackage(file, extendedFile) && !_importedFiles.contains(extendedFile))) { + errors.add(sourceDescription(file) + ": Message '" + Util.toString(message) + "' extends message '" + + Util.toString(extended) + "' of '" + sourceDescription(extendedFile) + + "', which does not declare option OpenWorld. Add 'option OpenWorld;' to '" + + sourceDescription(extendedFile) + "' to extend its messages in other files" + + " (a hierarchy without OpenWorld can only be split into files of the same package" + + " that are generated together)."); + } + } + + for (Definition inner : message.getDefinitions()) { + validateGeneralizations(file, inner, errors); + } + } + + private static boolean samePackage(DefinitionFile file, DefinitionFile other) { + QName pkg = file.getPackage(); + QName otherPkg = other.getPackage(); + if (pkg == null || otherPkg == null) { + return pkg == otherPkg; + } + return pkg.getNames().equals(otherPkg.getNames()); + } + /** * Rejects fields whose generated names clash with the names of other fields of the same message, * declared in the message itself or inherited from a generalization. diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedRecursive.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedRecursive.java new file mode 100644 index 00000000..4e76bd9f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNestedRecursive.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.nested; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; + +import de.haumacher.msgbuf.binary.OctetDataReader; +import de.haumacher.msgbuf.binary.OctetDataWriter; +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import junit.framework.TestCase; +import test.nested.recursive.Expr; +import test.nested.recursive.Node; + +/** + * Test case for specializations nested in their own generalization (issue #32). + */ +@SuppressWarnings("javadoc") +public class TestNestedRecursive extends TestCase { + + public void testJson() throws IOException { + Expr.Sum sum = createSum(); + String json = sum.toString(); + assertEquals("[\"Sum\",{\"label\":\"s\",\"operands\":[[\"Literal\",{\"label\":\"a\",\"value\":1}]," + + "[\"Sum\",{\"label\":\"\",\"operands\":[]}]],\"first\":{\"label\":\"\",\"value\":2}}]", json); + assertEquals(json, Expr.readExpr(new JsonReader(new StringR(json))).toString()); + } + + public void testBinary() throws IOException { + Expr.Sum sum = createSum(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + sum.writeTo(new OctetDataWriter(buffer)); + Expr copy = Expr.readExpr(new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))); + assertEquals(sum.toString(), copy.toString()); + } + + public void testXml() throws XMLStreamException { + Expr.Sum sum = createSum(); + StringWriter buffer = new StringWriter(); + sum.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + Expr copy = Expr.readExpr(XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(buffer.toString()))); + assertEquals(sum.toString(), copy.toString()); + } + + public void testFieldIndexes() { + // Inherited fields keep their index, own fields of the nested specializations follow. + assertEquals(1, Expr.Literal.LABEL__ID); + assertEquals(2, Expr.Literal.VALUE__ID); + assertEquals(2, Expr.Sum.OPERANDS__ID); + assertEquals(3, Expr.Sum.FIRST__ID); + assertEquals(3, Node.Special.WEIGHT__ID); + } + + public void testConcreteRoot() throws IOException { + // A hierarchy with a concrete root carries no type information, read through the specialization's reader. + Node.Special special = Node.Special.create().setWeight(4); + special.setName("s"); + special.addChildren(Node.create().setName("c")); + String json = special.toString(); + assertEquals("{\"name\":\"s\",\"children\":[{\"name\":\"c\",\"children\":[]}],\"weight\":4}", json); + assertEquals(json, Node.Special.readSpecial(new JsonReader(new StringR(json))).toString()); + } + + private static Expr.Sum createSum() { + Expr.Sum result = Expr.Sum.create(); + result.setLabel("s"); + result.addOperand(Expr.Literal.create().setValue(1).setLabel("a")); + result.addOperand(Expr.Sum.create()); + result.setFirst(Expr.Literal.create().setValue(2)); + return result; + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Expr.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Expr.java new file mode 100644 index 00000000..066b03e0 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Expr.java @@ -0,0 +1,229 @@ +package test.nested.recursive; + +/** + * Specializations nested in their own generalization (issue #32). + */ +public interface Expr extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.recursive.Expr} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.recursive.Expr.Literal}. */ + LITERAL, + + /** Type literal for {@link test.nested.recursive.Expr.Sum}. */ + SUM, + ; + + } + + /** Visitor interface for the {@link test.nested.recursive.Expr} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.nested.recursive.Expr.Literal}.*/ + R visit(test.nested.recursive.Expr.Literal self, A arg) throws E; + + /** Visit case for {@link test.nested.recursive.Expr.Sum}.*/ + R visit(test.nested.recursive.Expr.Sum self, A arg) throws E; + + } + public interface Literal extends test.nested.recursive.Expr { + + /** + * Creates a {@link test.nested.recursive.Expr.Literal} instance. + */ + static test.nested.recursive.Expr.Literal create() { + return new test.nested.recursive.impl.Expr_Impl.Literal_Impl(); + } + + /** Identifier for the {@link test.nested.recursive.Expr.Literal} type in JSON format. */ + String LITERAL__TYPE = "Literal"; + + /** @see #getValue() */ + String VALUE__PROP = "value"; + + /** Identifier for the {@link test.nested.recursive.Expr.Literal} type in binary format. */ + static final int LITERAL__TYPE_ID = 1; + + /** Identifier for the property {@link #getValue()} in binary format. */ + static final int VALUE__ID = 2; + + int getValue(); + + /** + * @see #getValue() + */ + test.nested.recursive.Expr.Literal setValue(int value); + + @Override + test.nested.recursive.Expr.Literal setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr.Literal readLiteral(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.recursive.impl.Expr_Impl.Literal_Impl result = new test.nested.recursive.impl.Expr_Impl.Literal_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr.Literal readLiteral(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.recursive.Expr.Literal result = test.nested.recursive.impl.Expr_Impl.Literal_Impl.readLiteral_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Literal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Literal readLiteral(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.recursive.impl.Expr_Impl.Literal_Impl.readLiteral_XmlContent(in); + } + + } + public interface Sum extends test.nested.recursive.Expr { + + /** + * Creates a {@link test.nested.recursive.Expr.Sum} instance. + */ + static test.nested.recursive.Expr.Sum create() { + return new test.nested.recursive.impl.Expr_Impl.Sum_Impl(); + } + + /** Identifier for the {@link test.nested.recursive.Expr.Sum} type in JSON format. */ + String SUM__TYPE = "Sum"; + + /** @see #getOperands() */ + String OPERANDS__PROP = "operands"; + + /** @see #getFirst() */ + String FIRST__PROP = "first"; + + /** Identifier for the {@link test.nested.recursive.Expr.Sum} type in binary format. */ + static final int SUM__TYPE_ID = 2; + + /** Identifier for the property {@link #getOperands()} in binary format. */ + static final int OPERANDS__ID = 2; + + /** Identifier for the property {@link #getFirst()} in binary format. */ + static final int FIRST__ID = 3; + + java.util.List getOperands(); + + /** + * @see #getOperands() + */ + test.nested.recursive.Expr.Sum setOperands(java.util.List value); + + /** + * Adds a value to the {@link #getOperands()} list. + */ + test.nested.recursive.Expr.Sum addOperand(test.nested.recursive.Expr value); + + /** + * Removes a value from the {@link #getOperands()} list. + */ + void removeOperand(test.nested.recursive.Expr value); + + test.nested.recursive.Expr.Literal getFirst(); + + /** + * @see #getFirst() + */ + test.nested.recursive.Expr.Sum setFirst(test.nested.recursive.Expr.Literal value); + + /** + * Checks, whether {@link #getFirst()} has a value. + */ + boolean hasFirst(); + + @Override + test.nested.recursive.Expr.Sum setLabel(String value); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr.Sum readSum(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.recursive.impl.Expr_Impl.Sum_Impl result = new test.nested.recursive.impl.Expr_Impl.Sum_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr.Sum readSum(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.recursive.Expr.Sum result = test.nested.recursive.impl.Expr_Impl.Sum_Impl.readSum_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Sum} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sum readSum(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.recursive.impl.Expr_Impl.Sum_Impl.readSum_XmlContent(in); + } + + } + + /** @see #getLabel() */ + String LABEL__PROP = "label"; + + /** Identifier for the property {@link #getLabel()} in binary format. */ + static final int LABEL__ID = 1; + + /** The type code of this instance. */ + TypeKind kind(); + + String getLabel(); + + /** + * @see #getLabel() + */ + test.nested.recursive.Expr setLabel(String value); + + @Override + public test.nested.recursive.Expr registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.recursive.Expr unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr readExpr(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.recursive.Expr result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.nested.recursive.Expr.Literal.LITERAL__TYPE: result = test.nested.recursive.Expr.Literal.readLiteral(in); break; + case test.nested.recursive.Expr.Sum.SUM__TYPE: result = test.nested.recursive.Expr.Sum.readSum(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** The binary identifier for this concrete type in the polymorphic {@link test.nested.recursive.Expr} hierarchy. */ + abstract int typeId(); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Expr readExpr(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + int typeField = in.nextName(); + assert typeField == 0; + int type = in.nextInt(); + test.nested.recursive.Expr result; + switch (type) { + case test.nested.recursive.Expr.Literal.LITERAL__TYPE_ID: result = test.nested.recursive.impl.Expr_Impl.Literal_Impl.readLiteral_Content(in); break; + case test.nested.recursive.Expr.Sum.SUM__TYPE_ID: result = test.nested.recursive.impl.Expr_Impl.Sum_Impl.readSum_Content(in); break; + default: result = null; while (in.hasNext()) {in.skipValue(); } + } + in.endObject(); + return result; + } + + /** Creates a new {@link Expr} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Expr readExpr(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.recursive.impl.Expr_Impl.readExpr_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Node.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Node.java new file mode 100644 index 00000000..a89ae399 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/Node.java @@ -0,0 +1,152 @@ +package test.nested.recursive; + +/** + * A concrete message with a nested specialization of itself. + */ +public interface Node extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.nested.recursive.Node} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.nested.recursive.Node}. */ + NODE, + + /** Type literal for {@link test.nested.recursive.Node.Special}. */ + SPECIAL, + ; + + } + public interface Special extends test.nested.recursive.Node { + + /** + * Creates a {@link test.nested.recursive.Node.Special} instance. + */ + static test.nested.recursive.Node.Special create() { + return new test.nested.recursive.impl.Node_Impl.Special_Impl(); + } + + /** Identifier for the {@link test.nested.recursive.Node.Special} type in JSON format. */ + String SPECIAL__TYPE = "Special"; + + /** @see #getWeight() */ + String WEIGHT__PROP = "weight"; + + /** Identifier for the property {@link #getWeight()} in binary format. */ + static final int WEIGHT__ID = 3; + + int getWeight(); + + /** + * @see #getWeight() + */ + test.nested.recursive.Node.Special setWeight(int value); + + @Override + test.nested.recursive.Node.Special setName(String value); + + @Override + test.nested.recursive.Node.Special setChildren(java.util.List value); + + @Override + test.nested.recursive.Node.Special addChildren(test.nested.recursive.Node value); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Node.Special readSpecial(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.recursive.impl.Node_Impl.Special_Impl result = new test.nested.recursive.impl.Node_Impl.Special_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Node.Special readSpecial(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.recursive.Node.Special result = test.nested.recursive.impl.Node_Impl.Special_Impl.readSpecial_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Special} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Special readSpecial(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.recursive.impl.Node_Impl.Special_Impl.readSpecial_XmlContent(in); + } + + } + + /** + * Creates a {@link test.nested.recursive.Node} instance. + */ + static test.nested.recursive.Node create() { + return new test.nested.recursive.impl.Node_Impl(); + } + + /** Identifier for the {@link test.nested.recursive.Node} type in JSON format. */ + String NODE__TYPE = "Node"; + + /** @see #getName() */ + String NAME__PROP = "name"; + + /** @see #getChildren() */ + String CHILDREN__PROP = "children"; + + /** Identifier for the property {@link #getName()} in binary format. */ + static final int NAME__ID = 1; + + /** Identifier for the property {@link #getChildren()} in binary format. */ + static final int CHILDREN__ID = 2; + + /** The type code of this instance. */ + TypeKind kind(); + + String getName(); + + /** + * @see #getName() + */ + test.nested.recursive.Node setName(String value); + + java.util.List getChildren(); + + /** + * @see #getChildren() + */ + test.nested.recursive.Node setChildren(java.util.List value); + + /** + * Adds a value to the {@link #getChildren()} list. + */ + test.nested.recursive.Node addChildren(test.nested.recursive.Node value); + + /** + * Removes a value from the {@link #getChildren()} list. + */ + void removeChildren(test.nested.recursive.Node value); + + @Override + public test.nested.recursive.Node registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.nested.recursive.Node unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Node readNode(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.nested.recursive.impl.Node_Impl result = new test.nested.recursive.impl.Node_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.nested.recursive.Node readNode(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.nested.recursive.Node result = test.nested.recursive.impl.Node_Impl.readNode_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Node} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Node readNode(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.nested.recursive.impl.Node_Impl.readNode_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Expr_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Expr_Impl.java new file mode 100644 index 00000000..7d70c0ac --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Expr_Impl.java @@ -0,0 +1,777 @@ +package test.nested.recursive.impl; + +/** + * Implementation of {@link test.nested.recursive.Expr}. + */ +public abstract class Expr_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.recursive.Expr { + /** + * Implementation of {@link test.nested.recursive.Expr.Literal}. + */ + public static class Literal_Impl extends test.nested.recursive.impl.Expr_Impl implements test.nested.recursive.Expr.Literal { + + private int _value = 0; + + /** + * Creates a {@link Literal_Impl} instance. + * + * @see test.nested.recursive.Expr.Literal#create() + */ + public Literal_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.LITERAL; + } + + @Override + public final int getValue() { + return _value; + } + + @Override + public test.nested.recursive.Expr.Literal setValue(int value) { + internalSetValue(value); + return this; + } + + /** Internal setter for {@link #getValue()} without chain call utility. */ + protected final void internalSetValue(int value) { + _listener.beforeSet(this, VALUE__PROP, value); + _value = value; + _listener.afterChanged(this, VALUE__PROP); + } + + @Override + public test.nested.recursive.Expr.Literal setLabel(String value) { + internalSetLabel(value); + return this; + } + + @Override + public String jsonType() { + return LITERAL__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + VALUE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.recursive.impl.Expr_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.recursive.impl.Expr_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case VALUE__PROP: return getValue(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case VALUE__PROP: internalSetValue((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(VALUE__PROP); + out.value(getValue()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case VALUE__PROP: setValue(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return LITERAL__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(VALUE__ID); + out.value(getValue()); + } + + /** Helper for creating an object of type {@link test.nested.recursive.Expr.Literal} from a polymorphic composition. */ + public static test.nested.recursive.Expr.Literal readLiteral_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.recursive.impl.Expr_Impl.Literal_Impl result = new Literal_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case VALUE__ID: setValue(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.recursive.Expr.Literal} type. */ + public static final String LITERAL__XML_ELEMENT = "literal"; + + /** XML attribute or element name of a {@link #getValue} property. */ + private static final String VALUE__XML_ATTR = "value"; + + @Override + public String getXmlTagName() { + return LITERAL__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(VALUE__XML_ATTR, Integer.toString(getValue())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.recursive.Expr.Literal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Literal_Impl readLiteral_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Literal_Impl result = new Literal_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case VALUE__XML_ATTR: { + setValue(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case VALUE__XML_ATTR: { + setValue(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.nested.recursive.Expr.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + /** + * Implementation of {@link test.nested.recursive.Expr.Sum}. + */ + public static class Sum_Impl extends test.nested.recursive.impl.Expr_Impl implements test.nested.recursive.Expr.Sum { + + private final java.util.List _operands = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.recursive.Expr element) { + _listener.beforeAdd(Sum_Impl.this, OPERANDS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.recursive.Expr element) { + _listener.afterRemove(Sum_Impl.this, OPERANDS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Sum_Impl.this, OPERANDS__PROP); + } + }; + + private test.nested.recursive.Expr.Literal _first = null; + + /** + * Creates a {@link Sum_Impl} instance. + * + * @see test.nested.recursive.Expr.Sum#create() + */ + public Sum_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.SUM; + } + + @Override + public final java.util.List getOperands() { + return _operands; + } + + @Override + public test.nested.recursive.Expr.Sum setOperands(java.util.List value) { + internalSetOperands(value); + return this; + } + + /** Internal setter for {@link #getOperands()} without chain call utility. */ + protected final void internalSetOperands(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'operands' cannot be null."); + _operands.clear(); + _operands.addAll(value); + } + + @Override + public test.nested.recursive.Expr.Sum addOperand(test.nested.recursive.Expr value) { + internalAddOperand(value); + return this; + } + + /** Implementation of {@link #addOperand(test.nested.recursive.Expr)} without chain call utility. */ + protected final void internalAddOperand(test.nested.recursive.Expr value) { + _operands.add(value); + } + + @Override + public final void removeOperand(test.nested.recursive.Expr value) { + _operands.remove(value); + } + + @Override + public final test.nested.recursive.Expr.Literal getFirst() { + return _first; + } + + @Override + public test.nested.recursive.Expr.Sum setFirst(test.nested.recursive.Expr.Literal value) { + internalSetFirst(value); + return this; + } + + /** Internal setter for {@link #getFirst()} without chain call utility. */ + protected final void internalSetFirst(test.nested.recursive.Expr.Literal value) { + _listener.beforeSet(this, FIRST__PROP, value); + _first = value; + _listener.afterChanged(this, FIRST__PROP); + } + + @Override + public final boolean hasFirst() { + return _first != null; + } + + @Override + public test.nested.recursive.Expr.Sum setLabel(String value) { + internalSetLabel(value); + return this; + } + + @Override + public String jsonType() { + return SUM__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + OPERANDS__PROP, + FIRST__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.recursive.impl.Expr_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.recursive.impl.Expr_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case OPERANDS__PROP: return getOperands(); + case FIRST__PROP: return getFirst(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case OPERANDS__PROP: internalSetOperands(de.haumacher.msgbuf.util.Conversions.asList(test.nested.recursive.Expr.class, value)); break; + case FIRST__PROP: internalSetFirst((test.nested.recursive.Expr.Literal) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(OPERANDS__PROP); + out.beginArray(); + for (test.nested.recursive.Expr x : getOperands()) { + x.writeTo(out); + } + out.endArray(); + if (hasFirst()) { + out.name(FIRST__PROP); + getFirst().writeContent(out); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case OPERANDS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.recursive.Expr.readExpr(in)); + } + in.endArray(); + setOperands(newValue); + } + break; + case FIRST__PROP: setFirst(test.nested.recursive.Expr.Literal.readLiteral(in)); break; + default: super.readField(in, field); + } + } + + @Override + public int typeId() { + return SUM__TYPE_ID; + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(OPERANDS__ID); + { + java.util.List values = getOperands(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.recursive.Expr x : values) { + x.writeTo(out); + } + out.endArray(); + } + if (hasFirst()) { + out.name(FIRST__ID); + getFirst().writeTo(out); + } + } + + /** Helper for creating an object of type {@link test.nested.recursive.Expr.Sum} from a polymorphic composition. */ + public static test.nested.recursive.Expr.Sum readSum_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.recursive.impl.Expr_Impl.Sum_Impl result = new Sum_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case OPERANDS__ID: { + in.beginArray(); + while (in.hasNext()) { + addOperand(test.nested.recursive.Expr.readExpr(in)); + } + in.endArray(); + } + break; + case FIRST__ID: setFirst(test.nested.recursive.Expr.Literal.readLiteral(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.recursive.Expr.Sum} type. */ + public static final String SUM__XML_ELEMENT = "sum"; + + /** XML attribute or element name of a {@link #getOperands} property. */ + private static final String OPERANDS__XML_ATTR = "operands"; + + /** XML attribute or element name of a {@link #getFirst} property. */ + private static final String FIRST__XML_ATTR = "first"; + + @Override + public String getXmlTagName() { + return SUM__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + out.writeStartElement(OPERANDS__XML_ATTR); + for (test.nested.recursive.Expr element : getOperands()) { + element.writeTo(out); + } + out.writeEndElement(); + if (hasFirst()) { + out.writeStartElement(FIRST__XML_ATTR); + getFirst().writeContent(out); + out.writeEndElement(); + } + } + + /** Creates a new {@link test.nested.recursive.Expr.Sum} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sum_Impl readSum_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Sum_Impl result = new Sum_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case OPERANDS__XML_ATTR: { + internalReadOperandsListXml(in); + break; + } + case FIRST__XML_ATTR: { + setFirst(test.nested.recursive.impl.Expr_Impl.Literal_Impl.readLiteral_XmlContent(in)); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + private void internalReadOperandsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addOperand(test.nested.recursive.impl.Expr_Impl.readExpr_XmlContent(in)); + } + } + + @Override + public R visit(test.nested.recursive.Expr.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + private String _label = ""; + + /** + * Creates a {@link Expr_Impl} instance. + */ + public Expr_Impl() { + super(); + } + + @Override + public final String getLabel() { + return _label; + } + + @Override + public test.nested.recursive.Expr setLabel(String value) { + internalSetLabel(value); + return this; + } + + /** Internal setter for {@link #getLabel()} without chain call utility. */ + protected final void internalSetLabel(String value) { + _listener.beforeSet(this, LABEL__PROP, value); + _label = value; + _listener.afterChanged(this, LABEL__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.recursive.Expr registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.recursive.Expr unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + LABEL__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case LABEL__PROP: return getLabel(); + default: return test.nested.recursive.Expr.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case LABEL__PROP: internalSetLabel((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(LABEL__PROP); + out.value(getLabel()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case LABEL__PROP: setLabel(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + out.name(0); + out.value(typeId()); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(LABEL__ID); + out.value(getLabel()); + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case LABEL__ID: setLabel(in.nextString()); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.recursive.Expr} type. */ + public static final String EXPR__XML_ELEMENT = "expr"; + + /** XML attribute or element name of a {@link #getLabel} property. */ + private static final String LABEL__XML_ATTR = "label"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(LABEL__XML_ATTR, getLabel()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.nested.recursive.Expr} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Expr_Impl readExpr_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.nested.recursive.impl.Expr_Impl.Literal_Impl.LITERAL__XML_ELEMENT: { + return test.nested.recursive.impl.Expr_Impl.Literal_Impl.readLiteral_XmlContent(in); + } + + case test.nested.recursive.impl.Expr_Impl.Sum_Impl.SUM__XML_ELEMENT: { + return test.nested.recursive.impl.Expr_Impl.Sum_Impl.readSum_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case LABEL__XML_ATTR: { + setLabel(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case LABEL__XML_ATTR: { + setLabel(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Node_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Node_Impl.java new file mode 100644 index 00000000..285af65b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/impl/Node_Impl.java @@ -0,0 +1,575 @@ +package test.nested.recursive.impl; + +/** + * Implementation of {@link test.nested.recursive.Node}. + */ +public class Node_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.nested.recursive.Node { + /** + * Implementation of {@link test.nested.recursive.Node.Special}. + */ + public static class Special_Impl extends test.nested.recursive.impl.Node_Impl implements test.nested.recursive.Node.Special { + + private int _weight = 0; + + /** + * Creates a {@link Special_Impl} instance. + * + * @see test.nested.recursive.Node.Special#create() + */ + public Special_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.SPECIAL; + } + + @Override + public final int getWeight() { + return _weight; + } + + @Override + public test.nested.recursive.Node.Special setWeight(int value) { + internalSetWeight(value); + return this; + } + + /** Internal setter for {@link #getWeight()} without chain call utility. */ + protected final void internalSetWeight(int value) { + _listener.beforeSet(this, WEIGHT__PROP, value); + _weight = value; + _listener.afterChanged(this, WEIGHT__PROP); + } + + @Override + public test.nested.recursive.Node.Special setName(String value) { + internalSetName(value); + return this; + } + + @Override + public test.nested.recursive.Node.Special setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + @Override + public test.nested.recursive.Node.Special addChildren(test.nested.recursive.Node value) { + internalAddChildren(value); + return this; + } + + @Override + public String jsonType() { + return SPECIAL__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WEIGHT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.nested.recursive.impl.Node_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.nested.recursive.impl.Node_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WEIGHT__PROP: return getWeight(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WEIGHT__PROP: internalSetWeight((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WEIGHT__PROP); + out.value(getWeight()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WEIGHT__PROP: setWeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WEIGHT__ID); + out.value(getWeight()); + } + + /** Helper for creating an object of type {@link test.nested.recursive.Node.Special} from a polymorphic composition. */ + public static test.nested.recursive.Node.Special readSpecial_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.recursive.impl.Node_Impl.Special_Impl result = new Special_Impl(); + result.readContent(in); + return result; + } + + @Override + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case WEIGHT__ID: setWeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.nested.recursive.Node.Special} type. */ + public static final String SPECIAL__XML_ELEMENT = "special"; + + /** XML attribute or element name of a {@link #getWeight} property. */ + private static final String WEIGHT__XML_ATTR = "weight"; + + @Override + public String getXmlTagName() { + return SPECIAL__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WEIGHT__XML_ATTR, Integer.toString(getWeight())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.nested.recursive.Node.Special} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Special_Impl readSpecial_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Special_Impl result = new Special_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WEIGHT__XML_ATTR: { + setWeight(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WEIGHT__XML_ATTR: { + setWeight(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + } + + private String _name = ""; + + private final java.util.List _children = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.nested.recursive.Node element) { + _listener.beforeAdd(Node_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.nested.recursive.Node element) { + _listener.afterRemove(Node_Impl.this, CHILDREN__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Node_Impl.this, CHILDREN__PROP); + } + }; + + /** + * Creates a {@link Node_Impl} instance. + * + * @see test.nested.recursive.Node#create() + */ + public Node_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.NODE; + } + + @Override + public final String getName() { + return _name; + } + + @Override + public test.nested.recursive.Node setName(String value) { + internalSetName(value); + return this; + } + + /** Internal setter for {@link #getName()} without chain call utility. */ + protected final void internalSetName(String value) { + _listener.beforeSet(this, NAME__PROP, value); + _name = value; + _listener.afterChanged(this, NAME__PROP); + } + + @Override + public final java.util.List getChildren() { + return _children; + } + + @Override + public test.nested.recursive.Node setChildren(java.util.List value) { + internalSetChildren(value); + return this; + } + + /** Internal setter for {@link #getChildren()} without chain call utility. */ + protected final void internalSetChildren(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'children' cannot be null."); + _children.clear(); + _children.addAll(value); + } + + @Override + public test.nested.recursive.Node addChildren(test.nested.recursive.Node value) { + internalAddChildren(value); + return this; + } + + /** Implementation of {@link #addChildren(test.nested.recursive.Node)} without chain call utility. */ + protected final void internalAddChildren(test.nested.recursive.Node value) { + _children.add(value); + } + + @Override + public final void removeChildren(test.nested.recursive.Node value) { + _children.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.nested.recursive.Node registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.nested.recursive.Node unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return NODE__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP, + CHILDREN__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NAME__PROP: return getName(); + case CHILDREN__PROP: return getChildren(); + default: return test.nested.recursive.Node.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NAME__PROP: internalSetName((String) value); break; + case CHILDREN__PROP: internalSetChildren(de.haumacher.msgbuf.util.Conversions.asList(test.nested.recursive.Node.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NAME__PROP); + out.value(getName()); + out.name(CHILDREN__PROP); + out.beginArray(); + for (test.nested.recursive.Node x : getChildren()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case CHILDREN__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.nested.recursive.Node.readNode(in)); + } + in.endArray(); + setChildren(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(NAME__ID); + out.value(getName()); + out.name(CHILDREN__ID); + { + java.util.List values = getChildren(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.OBJECT, values.size()); + for (test.nested.recursive.Node x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.nested.recursive.Node} from a polymorphic composition. */ + public static test.nested.recursive.Node readNode_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.nested.recursive.impl.Node_Impl result = new Node_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case NAME__ID: setName(in.nextString()); break; + case CHILDREN__ID: { + in.beginArray(); + while (in.hasNext()) { + addChildren(test.nested.recursive.Node.readNode(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.nested.recursive.Node} type. */ + public static final String NODE__XML_ELEMENT = "node"; + + /** XML attribute or element name of a {@link #getName} property. */ + private static final String NAME__XML_ATTR = "name"; + + /** XML attribute or element name of a {@link #getChildren} property. */ + private static final String CHILDREN__XML_ATTR = "children"; + + @Override + public String getXmlTagName() { + return NODE__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NAME__XML_ATTR, getName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeStartElement(CHILDREN__XML_ATTR); + for (test.nested.recursive.Node element : getChildren()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.nested.recursive.Node} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Node_Impl readNode_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Node_Impl result = new Node_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NAME__XML_ATTR: { + setName(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NAME__XML_ATTR: { + setName(in.getElementText()); + break; + } + case CHILDREN__XML_ATTR: { + internalReadChildrenListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadChildrenListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addChildren(test.nested.recursive.impl.Node_Impl.readNode_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/recursive.proto b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/recursive.proto new file mode 100644 index 00000000..03709b35 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/recursive/recursive.proto @@ -0,0 +1,28 @@ +package test.nested.recursive; + +/** + * Specializations nested in their own generalization (issue #32). + */ +abstract message Expr { + string label; + + message Literal extends Expr { + int value; + } + + message Sum extends Expr { + repeated Expr operands; + Literal first; + } +} + +/** A concrete message with a nested specialization of itself. */ +message Node { + string name; + + message Special extends Node { + int weight; + } + + repeated Node children; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestGeneralizations.java b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestGeneralizations.java new file mode 100644 index 00000000..5ccf76f8 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestGeneralizations.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.validation; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +import de.haumacher.msgbuf.generator.Generator; +import de.haumacher.msgbuf.generator.GeneratorException; +import de.haumacher.msgbuf.generator.parser.ParseException; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; +import junit.framework.TestCase; + +/** + * Test case for rejecting extensions of messages of other files that are inconsistent with + * option OpenWorld (issue #25), and inheritance cycles. + */ +@SuppressWarnings("javadoc") +public class TestGeneralizations extends TestCase { + + private static final File FIXTURES = new File("src/test/resources/reject/openworld"); + + private static final String HINT = " to extend its messages in other files (a hierarchy without OpenWorld can only" + + " be split into files of the same package that are generated together)."; + + public void testOtherPackage() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/ow/ext/other-package.proto: Message 'reject.ow.ext.Circle' extends message 'reject.ow.base.Shape' of" + + " 'reject/ow/base/closed.proto', which does not declare option OpenWorld. Add 'option OpenWorld;' to" + + " 'reject/ow/base/closed.proto'" + HINT, + "reject/ow/ext/other-package.proto: Message 'reject.ow.ext.Holder.Nested' extends message" + + " 'reject.ow.base.Shape' of 'reject/ow/base/closed.proto', which does not declare option OpenWorld." + + " Add 'option OpenWorld;' to 'reject/ow/base/closed.proto'" + HINT), + reject("ext/other-package.proto")); + } + + /** The base file is only imported, its readers were generated without the specialization. */ + public void testSamePackageImported() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/ow/base/same-package.proto: Message 'reject.ow.base.Square' extends message 'reject.ow.base.Shape'" + + " of 'reject/ow/base/closed.proto', which does not declare option OpenWorld. Add 'option OpenWorld;'" + + " to 'reject/ow/base/closed.proto'" + HINT), + reject("base/same-package.proto")); + } + + /** A closed hierarchy split into files of the same package that are generated together. */ + public void testSamePackageTogether() throws IOException, ParseException { + File out = newOutputDir(); + Generator generator = new Generator(); + generator.setOut(out); + generator.load(new File(FIXTURES, "base/closed.proto")); + generator.load(new File(FIXTURES, "base/same-package.proto")); + generator.generate(new XmlStreamingPlugin()); + assertTrue(new File(out, "reject/ow/base/Square.java").isFile()); + } + + /** Extending an intermediate requires OpenWorld in the intermediate's file, not only in the root's. */ + public void testIntermediateWithoutOpenWorld() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/ow/ext/leaf.proto: Message 'reject.ow.ext.Beep' extends message 'reject.ow.mid.Signal' of" + + " 'reject/ow/mid/mid.proto', which does not declare option OpenWorld. Add 'option OpenWorld;' to" + + " 'reject/ow/mid/mid.proto'" + HINT), + reject("ext/leaf.proto")); + } + + public void testCycle() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/ow/cycle.proto: Message 'reject.ow.A' is part of an inheritance cycle: reject.ow.A extends" + + " reject.ow.B extends reject.ow.A. Remove one of the extends clauses.", + "reject/ow/cycle.proto: Message 'reject.ow.B' is part of an inheritance cycle: reject.ow.B extends" + + " reject.ow.A extends reject.ow.B. Remove one of the extends clauses."), + reject("cycle.proto")); + } + + private List reject(String proto) throws IOException, ParseException { + File out = newOutputDir(); + Generator generator = new Generator(); + generator.setOut(out); + generator.load(new File(FIXTURES, proto)); + try { + generator.generate(new XmlStreamingPlugin()); + fail("Expected rejection of '" + proto + "'."); + return null; + } catch (GeneratorException ex) { + String[] written = out.list(); + assertTrue("No code must be generated for rejected definitions.", written == null || written.length == 0); + return ex.getErrors(); + } + } + + private File newOutputDir() throws IOException { + File target = new File("target"); + target.mkdirs(); + return Files.createTempDirectory(target.toPath(), getName()).toFile(); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/closed.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/closed.proto new file mode 100644 index 00000000..72838681 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/closed.proto @@ -0,0 +1,6 @@ +package reject.ow.base; + +/** A closed hierarchy (no option OpenWorld). */ +abstract message Shape { + string name; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/open.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/open.proto new file mode 100644 index 00000000..8b141184 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/open.proto @@ -0,0 +1,7 @@ +package reject.ow.base; + +option OpenWorld; + +abstract message Event { + string source; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/same-package.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/same-package.proto new file mode 100644 index 00000000..7fa9fc33 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/base/same-package.proto @@ -0,0 +1,7 @@ +package reject.ow.base; +import "closed.proto"; + +/** Splits the closed hierarchy into another file of the same package. */ +message Square extends Shape { + int side; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/cycle.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/cycle.proto new file mode 100644 index 00000000..607bf368 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/cycle.proto @@ -0,0 +1,9 @@ +package reject.ow; + +message A extends B { + string a; +} + +message B extends A { + string b; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/leaf.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/leaf.proto new file mode 100644 index 00000000..e9231233 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/leaf.proto @@ -0,0 +1,6 @@ +package reject.ow.ext; +import "../mid/mid.proto"; + +message Beep extends reject.ow.mid.Signal { + int duration; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/other-package.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/other-package.proto new file mode 100644 index 00000000..82c1e365 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/ext/other-package.proto @@ -0,0 +1,13 @@ +package reject.ow.ext; +import "../base/closed.proto"; + +/** Extends the closed hierarchy from another package (issue #25). */ +message Circle extends reject.ow.base.Shape { + int radius; +} + +message Holder { + message Nested extends reject.ow.base.Shape { + int size; + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/mid/mid.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/mid/mid.proto new file mode 100644 index 00000000..545bcc88 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/openworld/mid/mid.proto @@ -0,0 +1,7 @@ +package reject.ow.mid; +import "../base/open.proto"; + +/** An intermediate in a file without option OpenWorld. */ +abstract message Signal extends reject.ow.base.Event { + int level; +} From 7c34048f218b229e4e1429860e1decb0af2902a8 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 17:38:08 +0200 Subject: [PATCH 13/20] Let every reader of an OpenWorld hierarchy resolve the types of other files, in JSON and XML. The JSON reader of an abstract intermediate looked up the root's registry with a factory type it could not be assigned to, which did not compile (#26). The XML readers of an OpenWorld hierarchy had a closed switch over the types of their own file and could not read extension types at all (#27). As decided by the maintainer, a reader must consider all types of a hierarchy. The registration of an extension module now also registers XML element names, when both the extension and the root generate XML. The XML readers of the root and of all intermediates fall back to that registry. Intermediates accept a registered type only if it is one of their subtypes; otherwise they skip it like an unknown type, as the root reader does in JSON. The readers load the registrations themselves (`TypeRegistryLoader.ensureLoaded()`), since reading through an interface method did not trigger the static initializer that loaded them before. All concrete messages below an OpenWorld message of another file are registered, not only direct subtypes, and visitor dispatch and `kind()` of extension intermediates follow. Closes #26 Closes #27 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 + README.md | 7 + .../haumacher/msgbuf/generator/Generator.java | 60 +- .../msgbuf/generator/MessageGenerator.java | 56 +- .../generator/plugins/XmlStreamingPlugin.java | 61 +- .../src/test/java/test/nested/TestNested.java | 13 +- .../test/java/test/nested/owbase/Events.java | 11 + .../test/nested/owbase/impl/Events_Impl.java | 7 + .../test/nested/owcount/OwcountTypes.java | 1 + .../java/test/nested/owext/OwextTypes.java | 1 + .../java/test/openworld/TestOpenWorld.java | 18 + .../java/test/openworld/base/SSEEvent.java | 11 + .../openworld/base/impl/SSEEvent_Impl.java | 7 + .../openworld/deep/TestOpenWorldDeep.java | 373 ++++++++ .../java/test/openworld/deep/base/Animal.java | 103 +++ .../java/test/openworld/deep/base/Bird.java | 65 ++ .../java/test/openworld/deep/base/Dog.java | 44 + .../test/openworld/deep/base/Habitat.java | 257 ++++++ .../test/openworld/deep/base/Sparrow.java | 47 + .../java/test/openworld/deep/base/Zoo.java | 192 +++++ .../java/test/openworld/deep/base/base.proto | 61 ++ .../openworld/deep/base/impl/Animal_Impl.java | 227 +++++ .../openworld/deep/base/impl/Bird_Impl.java | 175 ++++ .../openworld/deep/base/impl/Dog_Impl.java | 178 ++++ .../deep/base/impl/Habitat_Impl.java | 797 +++++++++++++++++ .../deep/base/impl/Sparrow_Impl.java | 184 ++++ .../openworld/deep/base/impl/Zoo_Impl.java | 813 ++++++++++++++++++ .../test/openworld/deep/ext1/Ext1Types.java | 24 + .../java/test/openworld/deep/ext1/Fish.java | 65 ++ .../java/test/openworld/deep/ext1/Forest.java | 87 ++ .../java/test/openworld/deep/ext1/Parrot.java | 55 ++ .../java/test/openworld/deep/ext1/Pond.java | 72 ++ .../java/test/openworld/deep/ext1/Trout.java | 47 + .../java/test/openworld/deep/ext1/ext1.proto | 35 + .../openworld/deep/ext1/impl/Fish_Impl.java | 178 ++++ .../openworld/deep/ext1/impl/Forest_Impl.java | 312 +++++++ .../openworld/deep/ext1/impl/Parrot_Impl.java | 187 ++++ .../openworld/deep/ext1/impl/Pond_Impl.java | 315 +++++++ .../openworld/deep/ext1/impl/Trout_Impl.java | 184 ++++ .../java/test/openworld/deep/ext2/Eagle.java | 47 + .../test/openworld/deep/ext2/Ext2Types.java | 22 + .../java/test/openworld/deep/ext2/Raptor.java | 54 ++ .../java/test/openworld/deep/ext2/Shark.java | 55 ++ .../java/test/openworld/deep/ext2/ext2.proto | 18 + .../openworld/deep/ext2/impl/Eagle_Impl.java | 190 ++++ .../openworld/deep/ext2/impl/Raptor_Impl.java | 177 ++++ .../openworld/deep/ext2/impl/Shark_Impl.java | 187 ++++ .../java/test/openworld/ext1/Ext1Types.java | 1 + .../java/test/openworld/ext2/Ext2Types.java | 1 + .../de.haumacher.msgbuf.data.TypeRegistration | 2 + 50 files changed, 6068 insertions(+), 30 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/TestOpenWorldDeep.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Animal.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Bird.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Dog.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Habitat.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Sparrow.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Zoo.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Animal_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Bird_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Dog_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Habitat_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Sparrow_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Zoo_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Ext1Types.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Fish.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Forest.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Parrot.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Pond.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Trout.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/ext1.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Fish_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Forest_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Parrot_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Pond_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Trout_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Eagle.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Ext2Types.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Raptor.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Shark.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/ext2.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Eagle_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Raptor_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Shark_Impl.java diff --git a/CHANGELOG.md b/CHANGELOG.md index f9354651..97e9fbe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,20 @@ - **Redeclared fields** (#21): A field that redeclares an inherited field (directly or through any generalization, also across files), a field declared twice, and fields whose names generate the same Java names (e.g. `foo_bar` and `fooBar`) are rejected with an error. Before, the generator silently produced Java code that did not compile. +- **OpenWorld readers of abstract intermediates** (#26): The JSON reader of an abstract message below the root of an + `option OpenWorld` hierarchy (e.g. `Bird` in `Animal > Bird > Parrot`, top-level or nested) no longer fails to + compile. It reads the types of other files registered with the root, if they are specializations of the message; a + registered type of another subtree is skipped like an unknown type (the reader returns `null`). This also works for + abstract intermediates declared in extension files (which need `option OpenWorld` to be extended themselves), at any + depth. All concrete messages of an extension file below an OpenWorld message of another file are now registered, + also those extending a message of their own file. Visiting a type of an extension-file intermediate with a visitor + that does not know it calls `visitDefault()`, and such types return `null` from `kind()`. The JSON readers load the + type registrations themselves (before, reading an extension type returned `null` unless some implementation class + of the hierarchy had been initialized before). +- **OpenWorld XML readers** (#27): The XML readers of an `option OpenWorld` hierarchy (root and abstract intermediates) + now read the types of other files. The generated registration class (e.g. `Ext1Types`) additionally registers the + XML element name of each extension type with the root (`registerXml()`, `XML_REGISTRY`), if the files generate XML. + The wire formats are unchanged. ## 1.2.1 diff --git a/README.md b/README.md index 7f044439..f5532c8e 100644 --- a/README.md +++ b/README.md @@ -297,6 +297,13 @@ The base module's `.proto` files should be packaged as resources in its JAR (e.g The Maven plugin automatically resolves imports from compile-scope dependency JARs, so no file system paths to the base module are needed. +Readers of the hierarchy (of the root and of abstract intermediates) resolve the types of all registered +extension modules in JSON and XML format. The registration class registers the JSON type ID and, if XML is +generated, the XML element name of each extension type with the root of the hierarchy. A reader of an abstract +intermediate only accepts registered types that specialize the intermediate. An unknown type (or a registered +type of another subtree) is skipped, and the reader returns `null`. An abstract message of an extension file can +itself be extended in further files, if the extension file declares `option OpenWorld`, too. + Implications: - Implies `option NoBinary` (only JSON and XML serialization are supported) - Cannot be combined with `option NoInterfaces` diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 25ca5868..4e428968 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -241,7 +241,7 @@ public void generate(GeneratorPlugin plugin) { } List crossFileExtensions = findCrossFileExtensions(file); if (!crossFileExtensions.isEmpty()) { - String fqClassName = generateRegistrationClass(file, crossFileExtensions); + String fqClassName = generateRegistrationClass(file, crossFileExtensions, plugin); registrationClasses.add(fqClassName); } } @@ -778,15 +778,21 @@ private List findCrossFileExtensions(DefinitionFile file) { return result; } + /** + * Collects the concrete messages of the given file that must be registered with the registry of + * an option OpenWorld hierarchy. + * + *

+ * These are all concrete messages with a generalization defined in another file with + * option OpenWorld. The readers of this generalization (and of its generalizations) + * only find these types through the registry of the hierarchy root. This includes messages + * that extend a message of the same file that extends a message of another file, and messages + * that extend a message of an extension file. + *

+ */ private void collectCrossFileExtensions(MessageDef def, DefinitionFile file, List result) { - MessageDef extended = def.getExtendedDef(); - DefinitionFile extendedFile = extended == null ? null : Util.definingFile(extended); - if (extendedFile != null && extendedFile != file) { - if (Util.getFlag(extendedFile, "OpenWorld")) { - if (!def.isAbstract()) { - result.add(def); - } - } + if (!def.isAbstract() && hasOpenWorldGeneralizationInOtherFile(def, file)) { + result.add(def); } for (Definition inner : def.getDefinitions()) { if (inner instanceof MessageDef) { @@ -795,7 +801,27 @@ private void collectCrossFileExtensions(MessageDef def, DefinitionFile file, Lis } } - private String generateRegistrationClass(DefinitionFile file, List extensions) { + private static boolean hasOpenWorldGeneralizationInOtherFile(MessageDef def, DefinitionFile file) { + Set seen = new HashSet<>(); + for (MessageDef current = def.getExtendedDef(); current != null && seen.add(current); current = current.getExtendedDef()) { + DefinitionFile currentFile = Util.definingFile(current); + if (currentFile != file && Util.getFlag(currentFile, "OpenWorld")) { + return true; + } + } + return false; + } + + private static MessageDef hierarchyRoot(MessageDef def) { + Set seen = new HashSet<>(); + MessageDef result = def; + while (result.getExtendedDef() != null && seen.add(result)) { + result = result.getExtendedDef(); + } + return result; + } + + private String generateRegistrationClass(DefinitionFile file, List extensions, GeneratorPlugin plugin) { String packageName = CodeConvention.packageName(file.getPackage()); String[] parts = packageName.split("\\."); String baseName = parts[parts.length - 1]; @@ -804,6 +830,8 @@ private String generateRegistrationClass(DefinitionFile file, List e File dir = mkdir(file.getPackage()); File out = new File(dir, className + ".java"); + boolean xml = formats(file, plugin).contains(XmlStreamingPlugin.XML_FORMAT); + try (FileOutputStream os = new FileOutputStream(out)) { try (PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "utf-8"))) { System.out.println("Generating '" + out + "'."); @@ -817,15 +845,17 @@ private String generateRegistrationClass(DefinitionFile file, List e w.println("\t@Override"); w.println("\tpublic void register() {"); for (MessageDef ext : extensions) { - // Find the OpenWorld root type - MessageDef root = ext.getExtendedDef(); - while (root.getExtendedDef() != null) { - root = root.getExtendedDef(); - } + MessageDef root = hierarchyRoot(ext); String rootQName = CodeConvention.qTypeName(root); String extQName = CodeConvention.qTypeName(ext); String typeConstant = CodeConvention.jsonTypeConstant(ext); w.println("\t\t" + rootQName + ".register(" + extQName + "." + typeConstant + ", " + extQName + "::create);"); + if (xml && formats(Util.definingFile(root), plugin).contains(XmlStreamingPlugin.XML_FORMAT)) { + // The XML readers of the hierarchy dispatch unknown element names through the registry of the root. + String extImplQName = CodeConvention.qImplName(CodeConvention.IMPL_PACKAGE_SUFFIX, ext); + w.println("\t\t" + rootQName + "." + XmlStreamingPlugin.REGISTER_XML + "(" + extImplQName + "." + + XmlStreamingPlugin.xmlElementConstant(ext) + ", " + extQName + "::create);"); + } } w.println("\t}"); w.println(); diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index 4804f3a0..cf9a3431 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -664,8 +664,8 @@ private void generateKindLookup() { kindLookupComment(); line("public abstract " + TYPE_KIND_NAME + " kind();"); } - } else if (isCrossFileExtension()) { - // Cross-file extensions are not in the base's TypeKind enum, return null + } else if (isOpenWorldExtension()) { + // Types of other files are not in the TypeKind enum of an OpenWorld root, return null nl(); line("@Override"); line("public " + TYPE_KIND_NAME + " kind() {"); @@ -1374,11 +1374,26 @@ private void generateJson() { if (isOpenWorld()) { line("default: {"); { - line("de.haumacher.msgbuf.data.Factory factory = " + getOpenWorldRoot() + ".REGISTRY.get(type);"); - line("if (factory != null) {"); - { - line("result = factory.create();"); - line("result.readContent(in);"); + // Types of other files are only known through the registry of the hierarchy root, + // which is filled by the registrations found on the class path. + line("de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded();"); + String root = getOpenWorldRoot(); + if (_def.getExtendedDef() == null) { + line("de.haumacher.msgbuf.data.Factory factory = " + root + ".REGISTRY.get(type);"); + line("if (factory != null) {"); + { + line("result = factory.create();"); + line("result.readContent(in);"); + } + } else { + // The registry of the root may contain types that are no specializations of this type. + line("de.haumacher.msgbuf.data.Factory factory = " + root + ".REGISTRY.get(type);"); + line(root + " instance = factory == null ? null : factory.create();"); + line("if (instance instanceof " + thisType() + ") {"); + { + line("result = (" + thisType() + ") instance;"); + line("result.readContent(in);"); + } } line("} else {"); { @@ -2215,7 +2230,17 @@ private void generateVisitMethods() { line("public" + (_def.isAbstract() ? " final" : "") + " R visit(" + qTypeName(gen) + ".Visitor v, A arg) " + onVisitEx("throws E ") + "{"); { if (_def.isAbstract()) { - line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + if (isCrossFileExtension()) { + // The visitor of the generalization does not know this type. + line("if (v instanceof " + qTypeName(_def) + ".Visitor) {"); + { + line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + } + line("}"); + line("return v.visitDefault(this, arg);"); + } else { + line("return visit((" + qTypeName(_def) + ".Visitor) v, arg);"); + } } else if (isCrossFileExtension()) { line("if (v instanceof " + qTypeName(_def) + ".Visitor) {"); { @@ -2364,6 +2389,21 @@ private boolean isCrossFileExtension() { return genFile != Util.definingFile(_def) && Util.getFlag(genFile, "OpenWorld"); } + /** + * Whether the generated type belongs to an OpenWorld hierarchy whose root is defined in + * another file. + * + *

+ * Such a type is not known to the root, e.g. it is not listed in the root's TypeKind enum. + * In contrast to {@link #isCrossFileExtension()}, this also holds for a type that extends a + * message of its own file which in turn extends a message of another file. + *

+ */ + private boolean isOpenWorldExtension() { + DefinitionFile rootFile = Util.definingFile(getRoot(_def)); + return rootFile != Util.definingFile(_def) && Util.getFlag(rootFile, "OpenWorld"); + } + private List localSpecializations(MessageDef def) { return localSpecializations(def, Util.definingFile(_def)); } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index a40b0999..17d6451f 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -95,6 +95,21 @@ public FileGenerator messageInterfaceContents(Map options, Messa return new AbstractMessageGenerator(options) { @Override protected void generate() { + if (isOpenWorld(options) && def.isAbstract() && !def.hasExtends()) { + nl(); + line("/** Registry for dynamically registered subtypes by their XML element names. */"); + line("static final java.util.Map> " + XML_REGISTRY + " = new java.util.HashMap<>();"); + nl(); + line("/**"); + line(" * Registers a subtype factory for reading elements with the given name in XML format."); + line(" */"); + line("static void " + REGISTER_XML + "(String elementName, de.haumacher.msgbuf.data.Factory factory) {"); + { + line(XML_REGISTRY + ".put(elementName, factory);"); + } + line("}"); + } + nl(); line("/** Creates a new {@link " + typeName(def) + "} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */"); line("public static " + typeName(def) + " " + readerMethod(def) + "(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException {"); @@ -254,6 +269,19 @@ protected void generate() { line("default: {"); { + if (isOpenWorld(options)) { + // Types of other files are only known through the registry of the hierarchy root. + String root = qTypeName(openWorldRoot(def)); + line("de.haumacher.msgbuf.data.Factory factory = " + root + "." + XML_REGISTRY + ".get(in.getLocalName());"); + line(root + " instance = factory == null ? null : factory.create();"); + line("if (instance instanceof " + implName(def) + ") {"); + { + line(implName(def) + " result = (" + implName(def) + ") instance;"); + line("result.readContentXml(in);"); + line("return result;"); + } + line("}"); + } line("internalSkipUntilMatchingEndElement(in);"); line("return null;"); } @@ -499,6 +527,37 @@ String xmlTypeNameRef(MessageDef def) { }; } + /** + * Name of the registry of XML element names in the root interface of an + * option OpenWorld hierarchy. + */ + public static final String XML_REGISTRY = "XML_REGISTRY"; + + /** + * Name of the method in the root interface of an option OpenWorld hierarchy + * that registers a factory for an XML element name. + */ + public static final String REGISTER_XML = "registerXml"; + + /** + * Name of the constant with the XML element name of the given message in its implementation class. + */ + public static String xmlElementConstant(MessageDef def) { + return CodeUtil.allUpperCase(def.getName()) + "__XML_ELEMENT"; + } + + private static boolean isOpenWorld(Map options) { + return AbstractMessageGenerator.isTrue(options.get("OpenWorld"), false); + } + + private static MessageDef openWorldRoot(MessageDef def) { + MessageDef result = def; + while (result.getExtendedDef() != null) { + result = result.getExtendedDef(); + } + return result; + } + private boolean noXml(Map options) { return options.get("NoXml") != null; } @@ -669,7 +728,7 @@ String xmlFieldNameConstant(Field field) { } String xmlTypeNameConstant(MessageDef def) { - return CodeUtil.allUpperCase(def.getName()) + "__XML_ELEMENT"; + return xmlElementConstant(def); } String readListFieldMethod(Field field) { diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java index a9752731..6d35280c 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/TestNested.java @@ -223,9 +223,8 @@ public String visit(Zoo.Parrot self, Void arg) { * *

* OpenWorld implies NoBinary, so only JSON and XML apply. The extension types are discovered - * through the generated service descriptor in src/test/resources/META-INF/services. - * XML is checked for the local type only: the generated XML reader of an OpenWorld root does not - * consult the registry of extension types (for top-level roots neither). + * through the generated service descriptor in src/test/resources/META-INF/services, + * in JSON and in XML format (issue #27). *

*/ public void testOpenWorldCrossFile() throws IOException, XMLStreamException { @@ -251,9 +250,11 @@ public void testOpenWorldCrossFile() throws IOException, XMLStreamException { assertTrue(copy.getEvents().get(1) instanceof Patches.PatchEvent); assertTrue(copy.getEvents().get(2) instanceof CountEvent); - // XML: the local type of the base file is read back. - Events local = Events.create().addEvent(Events.TextEvent.create().setText("hi").setTimestamp(1)); - assertEquals(local.toString(), Events.readEvents(xmlReader(xml(local))).toString()); + // XML: the extension types are read back through the registry of XML element names. + Events xmlCopy = Events.readEvents(xmlReader(xml(events))); + assertEquals(expected, xmlCopy.toString()); + assertTrue(xmlCopy.getEvents().get(1) instanceof Patches.PatchEvent); + assertTrue(xmlCopy.getEvents().get(2) instanceof CountEvent); Events.Event.Visitor visitor = new Patches.PatchEvent.Visitor<>() { @Override diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java index 84f9f31d..8dad7ea3 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/Events.java @@ -66,6 +66,7 @@ static test.nested.owbase.Events.Event readEvent(de.haumacher.msgbuf.json.JsonRe switch (type) { case test.nested.owbase.Events.TextEvent.TEXT_EVENT__TYPE: result = test.nested.owbase.Events.TextEvent.readTextEvent(in); break; default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); de.haumacher.msgbuf.data.Factory factory = test.nested.owbase.Events.Event.REGISTRY.get(type); if (factory != null) { result = factory.create(); @@ -80,6 +81,16 @@ static test.nested.owbase.Events.Event readEvent(de.haumacher.msgbuf.json.JsonRe return result; } + /** Registry for dynamically registered subtypes by their XML element names. */ + static final java.util.Map> XML_REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for reading elements with the given name in XML format. + */ + static void registerXml(String elementName, de.haumacher.msgbuf.data.Factory factory) { + XML_REGISTRY.put(elementName, factory); + } + /** Creates a new {@link Event} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ public static Event readEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { in.nextTag(); diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java index 547e6ed4..d1d92011 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owbase/impl/Events_Impl.java @@ -155,6 +155,13 @@ public static Event_Impl readEvent_XmlContent(javax.xml.stream.XMLStreamReader i } default: { + de.haumacher.msgbuf.data.Factory factory = test.nested.owbase.Events.Event.XML_REGISTRY.get(in.getLocalName()); + test.nested.owbase.Events.Event instance = factory == null ? null : factory.create(); + if (instance instanceof Event_Impl) { + Event_Impl result = (Event_Impl) instance; + result.readContentXml(in); + return result; + } internalSkipUntilMatchingEndElement(in); return null; } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java index ac890314..2176adb8 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owcount/OwcountTypes.java @@ -8,6 +8,7 @@ public class OwcountTypes implements de.haumacher.msgbuf.data.TypeRegistration { @Override public void register() { test.nested.owbase.Events.Event.register(test.nested.owcount.CountEvent.COUNT_EVENT__TYPE, test.nested.owcount.CountEvent::create); + test.nested.owbase.Events.Event.registerXml(test.nested.owcount.impl.CountEvent_Impl.COUNT_EVENT__XML_ELEMENT, test.nested.owcount.CountEvent::create); } /** diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java index e792e17e..3d2f68ad 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/nested/owext/OwextTypes.java @@ -8,6 +8,7 @@ public class OwextTypes implements de.haumacher.msgbuf.data.TypeRegistration { @Override public void register() { test.nested.owbase.Events.Event.register(test.nested.owext.Patches.PatchEvent.PATCH_EVENT__TYPE, test.nested.owext.Patches.PatchEvent::create); + test.nested.owbase.Events.Event.registerXml(test.nested.owext.impl.Patches_Impl.PatchEvent_Impl.PATCH_EVENT__XML_ELEMENT, test.nested.owext.Patches.PatchEvent::create); } /** diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorld.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorld.java index c25ac546..0d5ba73e 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorld.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorld.java @@ -1,6 +1,12 @@ package test.openworld; import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; import de.haumacher.msgbuf.io.StringR; import de.haumacher.msgbuf.json.JsonReader; @@ -112,6 +118,18 @@ public void testUnknownType() throws IOException { assertNull(result); } + public void testExtensionRegistrationXml() throws XMLStreamException { + GraphPatchEvent graph = GraphPatchEvent.create().setControlId("c1").setPatch("p").setTimestamp(1); + AnalyticsPatchEvent analytics = AnalyticsPatchEvent.create().setMetricName("cpu").setMetricValue(0.5).setTimestamp(2); + for (SSEEvent event : new SSEEvent[] { graph, analytics, TextEvent.create().setText("t") }) { + StringWriter buffer = new StringWriter(); + event.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + SSEEvent copy = SSEEvent.readSSEEvent(XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(buffer.toString()))); + assertEquals(event.getClass(), copy.getClass()); + assertEquals(event.toString(), copy.toString()); + } + } + private SSEEvent readEvent(String json) throws IOException { return SSEEvent.readSSEEvent(new JsonReader(new StringR(json))); } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/SSEEvent.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/SSEEvent.java index 1b9ef5e4..a1d2a96a 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/SSEEvent.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/SSEEvent.java @@ -65,6 +65,7 @@ static test.openworld.base.SSEEvent readSSEEvent(de.haumacher.msgbuf.json.JsonRe switch (type) { case TextEvent.TEXT_EVENT__TYPE: result = test.openworld.base.TextEvent.readTextEvent(in); break; default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); de.haumacher.msgbuf.data.Factory factory = test.openworld.base.SSEEvent.REGISTRY.get(type); if (factory != null) { result = factory.create(); @@ -79,6 +80,16 @@ static test.openworld.base.SSEEvent readSSEEvent(de.haumacher.msgbuf.json.JsonRe return result; } + /** Registry for dynamically registered subtypes by their XML element names. */ + static final java.util.Map> XML_REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for reading elements with the given name in XML format. + */ + static void registerXml(String elementName, de.haumacher.msgbuf.data.Factory factory) { + XML_REGISTRY.put(elementName, factory); + } + /** Creates a new {@link SSEEvent} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ public static SSEEvent readSSEEvent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { in.nextTag(); diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/impl/SSEEvent_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/impl/SSEEvent_Impl.java index 0a59bf61..a096ce1a 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/impl/SSEEvent_Impl.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/base/impl/SSEEvent_Impl.java @@ -151,6 +151,13 @@ public static SSEEvent_Impl readSSEEvent_XmlContent(javax.xml.stream.XMLStreamRe } default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.base.SSEEvent.XML_REGISTRY.get(in.getLocalName()); + test.openworld.base.SSEEvent instance = factory == null ? null : factory.create(); + if (instance instanceof SSEEvent_Impl) { + SSEEvent_Impl result = (SSEEvent_Impl) instance; + result.readContentXml(in); + return result; + } internalSkipUntilMatchingEndElement(in); return null; } diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/TestOpenWorldDeep.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/TestOpenWorldDeep.java new file mode 100644 index 00000000..aa275445 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/TestOpenWorldDeep.java @@ -0,0 +1,373 @@ +package test.openworld.deep; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.net.URLClassLoader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import de.haumacher.msgbuf.data.TypeRegistryLoader; +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import de.haumacher.msgbuf.xml.XmlSerializable; +import junit.framework.TestCase; +import test.openworld.deep.base.Animal; +import test.openworld.deep.base.Bird; +import test.openworld.deep.base.Dog; +import test.openworld.deep.base.Habitat; +import test.openworld.deep.base.Sparrow; +import test.openworld.deep.base.Zoo; +import test.openworld.deep.ext1.Fish; +import test.openworld.deep.ext1.Forest; +import test.openworld.deep.ext1.Parrot; +import test.openworld.deep.ext1.Pond; +import test.openworld.deep.ext1.Trout; +import test.openworld.deep.ext2.Eagle; +import test.openworld.deep.ext2.Raptor; +import test.openworld.deep.ext2.Shark; + +/** + * Readers of OpenWorld hierarchies with abstract intermediates resolve the types of all files of + * the hierarchy in JSON and XML format (issues #26 and #27). + * + *

+ * The hierarchy {@link Animal} has the abstract intermediate {@link Bird} in the base file, the + * abstract intermediate {@link Fish} in the extension file ext1 and the abstract + * intermediate {@link Raptor} in the extension file ext2. The extension types are + * registered through the generated service descriptor in + * src/test/resources/META-INF/services. + *

+ */ +@SuppressWarnings("javadoc") +public class TestOpenWorldDeep extends TestCase { + + private static Parrot parrot() { + return Parrot.create().setWord("hello").setWingspan(0.5).setName("Polly"); + } + + private static Eagle eagle() { + return Eagle.create().setBald(true).setSpeed(80.5).setWingspan(2.0).setName("Sam"); + } + + private static Trout trout() { + return Trout.create().setRainbow(true).setFins(7).setName("Tim"); + } + + private static Shark shark() { + return Shark.create().setTeeth(300).setFins(8).setName("Bruce"); + } + + public void testExpectedJson() { + assertEquals("[\"Parrot\",{\"name\":\"Polly\",\"wingspan\":0.5,\"word\":\"hello\"}]", parrot().toString()); + assertEquals("{\"king\":[\"Shark\",{\"name\":\"Bruce\",\"fins\":8,\"teeth\":300}],\"school\":[]}", + Pond.create().setKing(shark()).toString()); + } + + public void testJsonThroughRootReader() throws IOException { + for (Animal animal : new Animal[] { parrot(), eagle(), trout(), shark(), Sparrow.create().setFlock(3), + Dog.create().setGood(true) }) { + Animal copy = Animal.readAnimal(json(animal.toString())); + assertEquals(animal.getClass(), copy.getClass()); + assertEquals(animal.toString(), copy.toString()); + } + } + + public void testJsonThroughIntermediateReader() throws IOException { + // Intermediate of the base file, types of the base file, the first and the second extension. + for (Bird bird : new Bird[] { parrot(), eagle(), Sparrow.create().setFlock(3) }) { + Bird copy = Bird.readBird(json(bird.toString())); + assertEquals(bird.getClass(), copy.getClass()); + assertEquals(bird.toString(), copy.toString()); + } + + // Intermediate of the first extension file, types of the same and of the second extension. + for (Fish fish : new Fish[] { trout(), shark() }) { + Fish copy = Fish.readFish(json(fish.toString())); + assertEquals(fish.getClass(), copy.getClass()); + assertEquals(fish.toString(), copy.toString()); + } + + // Intermediate at depth three of the second extension file. + Raptor copy = Raptor.readRaptor(json(eagle().toString())); + assertEquals(eagle().toString(), copy.toString()); + } + + public void testXmlThroughRootReader() throws XMLStreamException { + for (Animal animal : new Animal[] { parrot(), eagle(), trout(), shark(), Sparrow.create().setFlock(3), + Dog.create().setGood(true) }) { + Animal copy = Animal.readAnimal(xmlReader(xml(animal))); + assertEquals(animal.getClass(), copy.getClass()); + assertEquals(animal.toString(), copy.toString()); + } + } + + public void testXmlThroughIntermediateReader() throws XMLStreamException { + for (Bird bird : new Bird[] { parrot(), eagle(), Sparrow.create().setFlock(3) }) { + Bird copy = Bird.readBird(xmlReader(xml(bird))); + assertEquals(bird.getClass(), copy.getClass()); + assertEquals(bird.toString(), copy.toString()); + } + + for (Fish fish : new Fish[] { trout(), shark() }) { + Fish copy = Fish.readFish(xmlReader(xml(fish))); + assertEquals(fish.getClass(), copy.getClass()); + assertEquals(fish.toString(), copy.toString()); + } + + Raptor copy = Raptor.readRaptor(xmlReader(xml(eagle()))); + assertEquals(eagle().toString(), copy.toString()); + } + + /** + * Single, repeated and nested fields of the root and of an intermediate type. + */ + private static Zoo zoo() { + return Zoo.create() + .setStar(shark()) + .addAnimal(trout()) + .addAnimal(parrot()) + .addAnimal(Dog.create().setName("Rex")) + .addAnimal(eagle()) + .setFavorite(eagle()) + .addBird(parrot()) + .addBird(Sparrow.create().setName("Jack")) + .addBird(eagle()) + .setAviary(Zoo.Aviary.create() + .setBoss(parrot()) + .addResident(eagle()) + .addResident(parrot())); + } + + public void testFieldsJson() throws IOException { + Zoo zoo = zoo(); + String json = zoo.toString(); + Zoo copy = Zoo.readZoo(json(json)); + assertEquals(json, copy.toString()); + assertTrue(copy.getStar() instanceof Shark); + assertTrue(copy.getFavorite() instanceof Eagle); + assertTrue(copy.getBirds().get(0) instanceof Parrot); + assertTrue(copy.getAviary().getBoss() instanceof Parrot); + assertTrue(copy.getAviary().getResidents().get(0) instanceof Eagle); + + Pond pond = Pond.create().setKing(shark()).addSchool(trout()).addSchool(shark()); + assertEquals(pond.toString(), Pond.readPond(json(pond.toString())).toString()); + } + + public void testFieldsXml() throws XMLStreamException { + Zoo zoo = zoo(); + Zoo copy = Zoo.readZoo(xmlReader(xml(zoo))); + assertEquals(zoo.toString(), copy.toString()); + assertTrue(copy.getStar() instanceof Shark); + assertTrue(copy.getFavorite() instanceof Eagle); + assertTrue(copy.getAviary().getResidents().get(1) instanceof Parrot); + + Pond pond = Pond.create().setKing(shark()).addSchool(trout()).addSchool(shark()); + assertEquals(pond.toString(), Pond.readPond(xmlReader(xml(pond))).toString()); + } + + /** + * A nested OpenWorld hierarchy with a nested intermediate, extended by a nested type of another + * file. + */ + public void testNestedHierarchy() throws IOException, XMLStreamException { + Habitat habitat = Habitat.create() + .setTallest(Forest.Oak.create().setAge(200).setHeight(30).setSpecies("quercus")) + .addPlant(Habitat.Birch.create().setHeight(10)) + .addPlant(Forest.Oak.create().setAge(5)); + String json = habitat.toString(); + assertEquals(json, Habitat.readHabitat(json(json)).toString()); + assertEquals(json, Habitat.readHabitat(xmlReader(xml(habitat))).toString()); + + Forest.Oak oak = Forest.Oak.create().setAge(1); + assertEquals(oak.toString(), Habitat.Tree.readTree(json(oak.toString())).toString()); + assertEquals(oak.toString(), Habitat.Tree.readTree(xmlReader(xml(oak))).toString()); + } + + /** + * A reader of an intermediate treats a registered type of a sibling subtree like an unknown type: + * the value is skipped and the reader returns null, as the root reader does for an + * unknown type. + */ + public void testMismatchedAndUnknownTypeJson() throws IOException { + assertNull(Bird.readBird(json(trout().toString()))); + assertNull(Bird.readBird(json(shark().toString()))); + assertNull(Bird.readBird(json(Dog.create().toString()))); + assertNull(Fish.readFish(json(parrot().toString()))); + assertNull(Raptor.readRaptor(json(parrot().toString()))); + assertNull(Bird.readBird(json("[\"Unknown\",{\"name\":\"x\"}]"))); + assertNull(Animal.readAnimal(json("[\"Unknown\",{\"name\":\"x\"}]"))); + + // The skipped value is consumed completely: the reader continues with the next property. + Zoo zoo = Zoo.readZoo(json("{\"favorite\":" + trout() + ",\"star\":" + parrot() + "}")); + assertNull(zoo.getFavorite()); + assertEquals(parrot().toString(), zoo.getStar().toString()); + } + + public void testMismatchedAndUnknownTypeXml() throws XMLStreamException { + assertNull(Bird.readBird(xmlReader(xml(trout())))); + assertNull(Bird.readBird(xmlReader(xml(shark())))); + assertNull(Fish.readFish(xmlReader(xml(parrot())))); + assertNull(Raptor.readRaptor(xmlReader(xml(parrot())))); + assertNull(Bird.readBird(xmlReader(""))); + assertNull(Animal.readAnimal(xmlReader(""))); + + // The skipped element is consumed completely: the reader continues with the next element. + String xml = xml(Zoo.create().setFavorite(eagle()).setStar(parrot())) + .replace("", ""); + assertTrue(xml, xml.contains(" animals = new Animal.Visitor<>() { + @Override + public String visit(Sparrow self, Void arg) { + return "sparrow"; + } + + @Override + public String visit(Dog self, Void arg) { + return "dog"; + } + + @Override + public String visitDefault(Bird self, Void arg) { + return "bird:" + self.getName(); + } + + @Override + public String visitDefault(Animal self, Void arg) { + return "animal:" + self.getName(); + } + }; + assertEquals("sparrow", Sparrow.create().visit(animals, null)); + assertEquals("dog", Dog.create().visit(animals, null)); + assertEquals("bird:Polly", parrot().visit(animals, null)); + assertEquals("bird:Sam", eagle().visit(animals, null)); + assertEquals("animal:Tim", trout().visit(animals, null)); + assertEquals("animal:Bruce", shark().visit(animals, null)); + + // A visitor of the intermediate of an extension file handles its types. + class FishVisitor implements Animal.Visitor, Fish.Visitor { + @Override + public String visit(Sparrow self, Void arg) { + return "sparrow"; + } + + @Override + public String visit(Dog self, Void arg) { + return "dog"; + } + + @Override + public String visitDefault(Bird self, Void arg) { + return "bird"; + } + + @Override + public String visitDefault(Animal self, Void arg) { + return "animal"; + } + + @Override + public String visit(Trout self, Void arg) { + return "trout"; + } + + @Override + public String visitDefault(Fish self, Void arg) { + return "fish:" + self.getName(); + } + } + // Dispatched through the visitor of the root, which does not know the types of the extensions. + Animal.Visitor fishes = new FishVisitor(); + assertEquals("trout", trout().visit(fishes, null)); + assertEquals("fish:Bruce", shark().visit(fishes, null)); + assertEquals("bird", parrot().visit(fishes, null)); + assertEquals("dog", Dog.create().visit(fishes, null)); + + Animal.Visitor sharks = new FishVisitor() { + @Override + public String visitDefault(Fish self, Void arg) { + return self instanceof Shark ? "shark" : "other"; + } + }; + assertEquals("shark", shark().visit(sharks, null)); + + Bird.Visitor parrots = new Parrot.Visitor<>() { + @Override + public String visit(Sparrow self, Void arg) { + return "sparrow"; + } + + @Override + public String visit(Parrot self, Void arg) { + return "parrot:" + self.getWord(); + } + + @Override + public String visitDefault(Bird self, Void arg) { + return "bird"; + } + }; + assertEquals("parrot:hello", parrot().visit(parrots, null)); + assertEquals("bird", eagle().visit(parrots, null)); + assertEquals("sparrow", Sparrow.create().visit(parrots, null)); + } + + /** + * The JSON readers, static methods of interfaces, load the registrations of the extension types + * even if no implementation class of the hierarchy has been initialized before. + */ + public void testFreshReaderLoadsRegistrations() throws Exception { + assertEquals(Parrot.class.getName(), readInFreshClassLoader(Animal.class, "readAnimal", parrot().toString())); + assertEquals(Shark.class.getName(), readInFreshClassLoader(Fish.class, "readFish", shark().toString())); + } + + /** + * Reads the given JSON with the given reader method in a class loader that has not yet loaded + * any class of the tested hierarchy, and returns the name of the data interface of the result. + */ + private static String readInFreshClassLoader(Class type, String readMethod, String json) throws Exception { + URL testClasses = TestOpenWorldDeep.class.getProtectionDomain().getCodeSource().getLocation(); + URL apiClasses = TypeRegistryLoader.class.getProtectionDomain().getCodeSource().getLocation(); + Thread thread = Thread.currentThread(); + ClassLoader before = thread.getContextClassLoader(); + try (URLClassLoader loader = new URLClassLoader(new URL[] { testClasses, apiClasses }, + ClassLoader.getPlatformClassLoader())) { + // The service loader of the registrations uses the context class loader. + thread.setContextClassLoader(loader); + Class reader = loader.loadClass(JsonReader.class.getName()); + Object in = reader.getConstructor(loader.loadClass("de.haumacher.msgbuf.io.Reader")) + .newInstance(loader.loadClass(StringR.class.getName()).getConstructor(String.class).newInstance(json)); + Object result = loader.loadClass(type.getName()).getMethod(readMethod, reader).invoke(null, in); + assertNotNull(result); + assertNotSame(type, result.getClass().getInterfaces()[0]); + return result.getClass().getInterfaces()[0].getName(); + } finally { + thread.setContextClassLoader(before); + } + } + + private static JsonReader json(String data) { + return new JsonReader(new StringR(data)); + } + + private static String xml(XmlSerializable value) throws XMLStreamException { + StringWriter buffer = new StringWriter(); + value.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + return buffer.toString(); + } + + private static XMLStreamReader xmlReader(String xml) throws XMLStreamException { + return XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Animal.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Animal.java new file mode 100644 index 00000000..35e2aaac --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Animal.java @@ -0,0 +1,103 @@ +package test.openworld.deep.base; + +/** + * Root of an OpenWorld hierarchy with abstract intermediates (issues #26, #27). + */ +public interface Animal extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.openworld.deep.base.Animal} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.openworld.deep.base.Sparrow}. */ + SPARROW, + + /** Type literal for {@link test.openworld.deep.base.Dog}. */ + DOG, + ; + + } + + /** Registry for dynamically registered subtypes. */ + static final java.util.Map> REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for polymorphic deserialization. + */ + static void register(String typeId, de.haumacher.msgbuf.data.Factory factory) { + REGISTRY.put(typeId, factory); + } + + /** Visitor interface for the {@link test.openworld.deep.base.Animal} hierarchy.*/ + public interface Visitor extends test.openworld.deep.base.Bird.Visitor { + + /** Visit case for {@link test.openworld.deep.base.Dog}.*/ + R visit(test.openworld.deep.base.Dog self, A arg) throws E; + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.openworld.deep.base.Animal self, A arg) throws E; + + } + + /** @see #getName() */ + String NAME__PROP = "name"; + + /** The type code of this instance. */ + TypeKind kind(); + + String getName(); + + /** + * @see #getName() + */ + test.openworld.deep.base.Animal setName(String value); + + @Override + public test.openworld.deep.base.Animal registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.base.Animal unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Animal readAnimal(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.Animal result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case Sparrow.SPARROW__TYPE: result = test.openworld.deep.base.Sparrow.readSparrow(in); break; + case Dog.DOG__TYPE: result = test.openworld.deep.base.Dog.readDog(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.REGISTRY.get(type); + if (factory != null) { + result = factory.create(); + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Registry for dynamically registered subtypes by their XML element names. */ + static final java.util.Map> XML_REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for reading elements with the given name in XML format. + */ + static void registerXml(String elementName, de.haumacher.msgbuf.data.Factory factory) { + XML_REGISTRY.put(elementName, factory); + } + + /** Creates a new {@link Animal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Animal readAnimal(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Animal_Impl.readAnimal_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Bird.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Bird.java new file mode 100644 index 00000000..3e914bd1 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Bird.java @@ -0,0 +1,65 @@ +package test.openworld.deep.base; + +/** + * Abstract intermediate of the base file, extended in other files. + */ +public interface Bird extends test.openworld.deep.base.Animal { + + /** Visitor interface for the {@link test.openworld.deep.base.Bird} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.openworld.deep.base.Sparrow}.*/ + R visit(test.openworld.deep.base.Sparrow self, A arg) throws E; + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.openworld.deep.base.Bird self, A arg) throws E; + + } + + /** @see #getWingspan() */ + String WINGSPAN__PROP = "wingspan"; + + double getWingspan(); + + /** + * @see #getWingspan() + */ + test.openworld.deep.base.Bird setWingspan(double value); + + @Override + test.openworld.deep.base.Bird setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Bird readBird(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.Bird result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case Sparrow.SPARROW__TYPE: result = test.openworld.deep.base.Sparrow.readSparrow(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.REGISTRY.get(type); + test.openworld.deep.base.Animal instance = factory == null ? null : factory.create(); + if (instance instanceof test.openworld.deep.base.Bird) { + result = (test.openworld.deep.base.Bird) instance; + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Creates a new {@link Bird} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Bird readBird(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Bird_Impl.readBird_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Dog.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Dog.java new file mode 100644 index 00000000..dd7c194c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Dog.java @@ -0,0 +1,44 @@ +package test.openworld.deep.base; + +/** + * Local leaf of a sibling subtree. + */ +public interface Dog extends test.openworld.deep.base.Animal { + + /** + * Creates a {@link test.openworld.deep.base.Dog} instance. + */ + static test.openworld.deep.base.Dog create() { + return new test.openworld.deep.base.impl.Dog_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Dog} type in JSON format. */ + String DOG__TYPE = "Dog"; + + /** @see #isGood() */ + String GOOD__PROP = "good"; + + boolean isGood(); + + /** + * @see #isGood() + */ + test.openworld.deep.base.Dog setGood(boolean value); + + @Override + test.openworld.deep.base.Dog setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Dog readDog(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Dog_Impl result = new test.openworld.deep.base.impl.Dog_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Dog} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Dog readDog(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Dog_Impl.readDog_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Habitat.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Habitat.java new file mode 100644 index 00000000..0466c48d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Habitat.java @@ -0,0 +1,257 @@ +package test.openworld.deep.base; + +/** + * A nested OpenWorld hierarchy with an abstract intermediate. + */ +public interface Habitat extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Plant extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.openworld.deep.base.Habitat.Plant} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.openworld.deep.base.Habitat.Birch}. */ + BIRCH, + ; + + } + + /** Registry for dynamically registered subtypes. */ + static final java.util.Map> REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for polymorphic deserialization. + */ + static void register(String typeId, de.haumacher.msgbuf.data.Factory factory) { + REGISTRY.put(typeId, factory); + } + + /** Visitor interface for the {@link test.openworld.deep.base.Habitat.Plant} hierarchy.*/ + public interface Visitor extends test.openworld.deep.base.Habitat.Tree.Visitor { + + // Pure sum interface. + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.openworld.deep.base.Habitat.Plant self, A arg) throws E; + + } + + /** @see #getSpecies() */ + String SPECIES__PROP = "species"; + + /** The type code of this instance. */ + TypeKind kind(); + + String getSpecies(); + + /** + * @see #getSpecies() + */ + test.openworld.deep.base.Habitat.Plant setSpecies(String value); + + @Override + public test.openworld.deep.base.Habitat.Plant registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.base.Habitat.Plant unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Habitat.Plant readPlant(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.Habitat.Plant result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.openworld.deep.base.Habitat.Birch.BIRCH__TYPE: result = test.openworld.deep.base.Habitat.Birch.readBirch(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Habitat.Plant.REGISTRY.get(type); + if (factory != null) { + result = factory.create(); + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Registry for dynamically registered subtypes by their XML element names. */ + static final java.util.Map> XML_REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for reading elements with the given name in XML format. + */ + static void registerXml(String elementName, de.haumacher.msgbuf.data.Factory factory) { + XML_REGISTRY.put(elementName, factory); + } + + /** Creates a new {@link Plant} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Plant readPlant(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Habitat_Impl.Plant_Impl.readPlant_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Tree extends test.openworld.deep.base.Habitat.Plant { + + /** Visitor interface for the {@link test.openworld.deep.base.Habitat.Tree} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.openworld.deep.base.Habitat.Birch}.*/ + R visit(test.openworld.deep.base.Habitat.Birch self, A arg) throws E; + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.openworld.deep.base.Habitat.Tree self, A arg) throws E; + + } + + /** @see #getHeight() */ + String HEIGHT__PROP = "height"; + + int getHeight(); + + /** + * @see #getHeight() + */ + test.openworld.deep.base.Habitat.Tree setHeight(int value); + + @Override + test.openworld.deep.base.Habitat.Tree setSpecies(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Habitat.Tree readTree(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.Habitat.Tree result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case test.openworld.deep.base.Habitat.Birch.BIRCH__TYPE: result = test.openworld.deep.base.Habitat.Birch.readBirch(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Habitat.Plant.REGISTRY.get(type); + test.openworld.deep.base.Habitat.Plant instance = factory == null ? null : factory.create(); + if (instance instanceof test.openworld.deep.base.Habitat.Tree) { + result = (test.openworld.deep.base.Habitat.Tree) instance; + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Creates a new {@link Tree} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Tree readTree(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl.readTree_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + + } + public interface Birch extends test.openworld.deep.base.Habitat.Tree { + + /** + * Creates a {@link test.openworld.deep.base.Habitat.Birch} instance. + */ + static test.openworld.deep.base.Habitat.Birch create() { + return new test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Habitat.Birch} type in JSON format. */ + String BIRCH__TYPE = "Birch"; + + @Override + test.openworld.deep.base.Habitat.Birch setHeight(int value); + + @Override + test.openworld.deep.base.Habitat.Birch setSpecies(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Habitat.Birch readBirch(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl result = new test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Birch} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Birch readBirch(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl.readBirch_XmlContent(in); + } + + } + + /** + * Creates a {@link test.openworld.deep.base.Habitat} instance. + */ + static test.openworld.deep.base.Habitat create() { + return new test.openworld.deep.base.impl.Habitat_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Habitat} type in JSON format. */ + String HABITAT__TYPE = "Habitat"; + + /** @see #getTallest() */ + String TALLEST__PROP = "tallest"; + + /** @see #getPlants() */ + String PLANTS__PROP = "plants"; + + test.openworld.deep.base.Habitat.Tree getTallest(); + + /** + * @see #getTallest() + */ + test.openworld.deep.base.Habitat setTallest(test.openworld.deep.base.Habitat.Tree value); + + /** + * Checks, whether {@link #getTallest()} has a value. + */ + boolean hasTallest(); + + java.util.List getPlants(); + + /** + * @see #getPlants() + */ + test.openworld.deep.base.Habitat setPlants(java.util.List value); + + /** + * Adds a value to the {@link #getPlants()} list. + */ + test.openworld.deep.base.Habitat addPlant(test.openworld.deep.base.Habitat.Plant value); + + /** + * Removes a value from the {@link #getPlants()} list. + */ + void removePlant(test.openworld.deep.base.Habitat.Plant value); + + @Override + public test.openworld.deep.base.Habitat registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.base.Habitat unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Habitat readHabitat(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Habitat_Impl result = new test.openworld.deep.base.impl.Habitat_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Habitat} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Habitat readHabitat(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Habitat_Impl.readHabitat_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Sparrow.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Sparrow.java new file mode 100644 index 00000000..07c7228c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Sparrow.java @@ -0,0 +1,47 @@ +package test.openworld.deep.base; + +/** + * Local leaf below the intermediate. + */ +public interface Sparrow extends test.openworld.deep.base.Bird { + + /** + * Creates a {@link test.openworld.deep.base.Sparrow} instance. + */ + static test.openworld.deep.base.Sparrow create() { + return new test.openworld.deep.base.impl.Sparrow_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Sparrow} type in JSON format. */ + String SPARROW__TYPE = "Sparrow"; + + /** @see #getFlock() */ + String FLOCK__PROP = "flock"; + + int getFlock(); + + /** + * @see #getFlock() + */ + test.openworld.deep.base.Sparrow setFlock(int value); + + @Override + test.openworld.deep.base.Sparrow setWingspan(double value); + + @Override + test.openworld.deep.base.Sparrow setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Sparrow readSparrow(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Sparrow_Impl result = new test.openworld.deep.base.impl.Sparrow_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Sparrow} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sparrow readSparrow(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Sparrow_Impl.readSparrow_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Zoo.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Zoo.java new file mode 100644 index 00000000..7e083adc --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/Zoo.java @@ -0,0 +1,192 @@ +package test.openworld.deep.base; + +/** + * Holder of values of the hierarchy in single, repeated and nested fields. + */ +public interface Zoo extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + /** + * A nested message with fields of the hierarchy. + */ + public interface Aviary extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.openworld.deep.base.Zoo.Aviary} instance. + */ + static test.openworld.deep.base.Zoo.Aviary create() { + return new test.openworld.deep.base.impl.Zoo_Impl.Aviary_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Zoo.Aviary} type in JSON format. */ + String AVIARY__TYPE = "Aviary"; + + /** @see #getBoss() */ + String BOSS__PROP = "boss"; + + /** @see #getResidents() */ + String RESIDENTS__PROP = "residents"; + + test.openworld.deep.base.Bird getBoss(); + + /** + * @see #getBoss() + */ + test.openworld.deep.base.Zoo.Aviary setBoss(test.openworld.deep.base.Bird value); + + /** + * Checks, whether {@link #getBoss()} has a value. + */ + boolean hasBoss(); + + java.util.List getResidents(); + + /** + * @see #getResidents() + */ + test.openworld.deep.base.Zoo.Aviary setResidents(java.util.List value); + + /** + * Adds a value to the {@link #getResidents()} list. + */ + test.openworld.deep.base.Zoo.Aviary addResident(test.openworld.deep.base.Bird value); + + /** + * Removes a value from the {@link #getResidents()} list. + */ + void removeResident(test.openworld.deep.base.Bird value); + + @Override + public test.openworld.deep.base.Zoo.Aviary registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.base.Zoo.Aviary unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Zoo.Aviary readAviary(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Zoo_Impl.Aviary_Impl result = new test.openworld.deep.base.impl.Zoo_Impl.Aviary_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Aviary} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Aviary readAviary(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Zoo_Impl.Aviary_Impl.readAviary_XmlContent(in); + } + + } + + /** + * Creates a {@link test.openworld.deep.base.Zoo} instance. + */ + static test.openworld.deep.base.Zoo create() { + return new test.openworld.deep.base.impl.Zoo_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.base.Zoo} type in JSON format. */ + String ZOO__TYPE = "Zoo"; + + /** @see #getStar() */ + String STAR__PROP = "star"; + + /** @see #getAnimals() */ + String ANIMALS__PROP = "animals"; + + /** @see #getFavorite() */ + String FAVORITE__PROP = "favorite"; + + /** @see #getBirds() */ + String BIRDS__PROP = "birds"; + + /** @see #getAviary() */ + String AVIARY__PROP = "aviary"; + + test.openworld.deep.base.Animal getStar(); + + /** + * @see #getStar() + */ + test.openworld.deep.base.Zoo setStar(test.openworld.deep.base.Animal value); + + /** + * Checks, whether {@link #getStar()} has a value. + */ + boolean hasStar(); + + java.util.List getAnimals(); + + /** + * @see #getAnimals() + */ + test.openworld.deep.base.Zoo setAnimals(java.util.List value); + + /** + * Adds a value to the {@link #getAnimals()} list. + */ + test.openworld.deep.base.Zoo addAnimal(test.openworld.deep.base.Animal value); + + /** + * Removes a value from the {@link #getAnimals()} list. + */ + void removeAnimal(test.openworld.deep.base.Animal value); + + test.openworld.deep.base.Bird getFavorite(); + + /** + * @see #getFavorite() + */ + test.openworld.deep.base.Zoo setFavorite(test.openworld.deep.base.Bird value); + + /** + * Checks, whether {@link #getFavorite()} has a value. + */ + boolean hasFavorite(); + + java.util.List getBirds(); + + /** + * @see #getBirds() + */ + test.openworld.deep.base.Zoo setBirds(java.util.List value); + + /** + * Adds a value to the {@link #getBirds()} list. + */ + test.openworld.deep.base.Zoo addBird(test.openworld.deep.base.Bird value); + + /** + * Removes a value from the {@link #getBirds()} list. + */ + void removeBird(test.openworld.deep.base.Bird value); + + test.openworld.deep.base.Zoo.Aviary getAviary(); + + /** + * @see #getAviary() + */ + test.openworld.deep.base.Zoo setAviary(test.openworld.deep.base.Zoo.Aviary value); + + /** + * Checks, whether {@link #getAviary()} has a value. + */ + boolean hasAviary(); + + @Override + public test.openworld.deep.base.Zoo registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.base.Zoo unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.base.Zoo readZoo(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.base.impl.Zoo_Impl result = new test.openworld.deep.base.impl.Zoo_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Zoo} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Zoo readZoo(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.base.impl.Zoo_Impl.readZoo_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/base.proto b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/base.proto new file mode 100644 index 00000000..08f4b8d5 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/base.proto @@ -0,0 +1,61 @@ +package test.openworld.deep.base; + +option OpenWorld; + +/** Root of an OpenWorld hierarchy with abstract intermediates (issues #26, #27). */ +abstract message Animal { + string name; +} + +/** Abstract intermediate of the base file, extended in other files. */ +abstract message Bird extends Animal { + double wingspan; +} + +/** Local leaf below the intermediate. */ +message Sparrow extends Bird { + int32 flock; +} + +/** Local leaf of a sibling subtree. */ +message Dog extends Animal { + bool good; +} + +/** Holder of values of the hierarchy in single, repeated and nested fields. */ +message Zoo { + Animal star; + + repeated Animal animals; + + Bird favorite; + + repeated Bird birds; + + /** A nested message with fields of the hierarchy. */ + message Aviary { + Bird boss; + + repeated Bird residents; + } + + Aviary aviary; +} + +/** A nested OpenWorld hierarchy with an abstract intermediate. */ +message Habitat { + abstract message Plant { + string species; + } + + abstract message Tree extends Plant { + int32 height; + } + + message Birch extends Tree { + } + + Tree tallest; + + repeated Plant plants; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Animal_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Animal_Impl.java new file mode 100644 index 00000000..ef183063 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Animal_Impl.java @@ -0,0 +1,227 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Animal}. + */ +public abstract class Animal_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.base.Animal { + + static { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + } + + private String _name = ""; + + /** + * Creates a {@link Animal_Impl} instance. + */ + public Animal_Impl() { + super(); + } + + @Override + public final String getName() { + return _name; + } + + @Override + public test.openworld.deep.base.Animal setName(String value) { + internalSetName(value); + return this; + } + + /** Internal setter for {@link #getName()} without chain call utility. */ + protected final void internalSetName(String value) { + _listener.beforeSet(this, NAME__PROP, value); + _name = value; + _listener.afterChanged(this, NAME__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.base.Animal registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.base.Animal unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NAME__PROP: return getName(); + default: return test.openworld.deep.base.Animal.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NAME__PROP: internalSetName((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NAME__PROP); + out.value(getName()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Animal} type. */ + public static final String ANIMAL__XML_ELEMENT = "animal"; + + /** XML attribute or element name of a {@link #getName} property. */ + private static final String NAME__XML_ATTR = "name"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NAME__XML_ATTR, getName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Animal} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Animal_Impl readAnimal_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case Sparrow_Impl.SPARROW__XML_ELEMENT: { + return test.openworld.deep.base.impl.Sparrow_Impl.readSparrow_XmlContent(in); + } + + case Dog_Impl.DOG__XML_ELEMENT: { + return test.openworld.deep.base.impl.Dog_Impl.readDog_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.XML_REGISTRY.get(in.getLocalName()); + test.openworld.deep.base.Animal instance = factory == null ? null : factory.create(); + if (instance instanceof Animal_Impl) { + Animal_Impl result = (Animal_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NAME__XML_ATTR: { + setName(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NAME__XML_ATTR: { + setName(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Bird_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Bird_Impl.java new file mode 100644 index 00000000..8d503afb --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Bird_Impl.java @@ -0,0 +1,175 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Bird}. + */ +public abstract class Bird_Impl extends test.openworld.deep.base.impl.Animal_Impl implements test.openworld.deep.base.Bird { + + private double _wingspan = 0.0d; + + /** + * Creates a {@link Bird_Impl} instance. + */ + public Bird_Impl() { + super(); + } + + @Override + public final double getWingspan() { + return _wingspan; + } + + @Override + public test.openworld.deep.base.Bird setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + /** Internal setter for {@link #getWingspan()} without chain call utility. */ + protected final void internalSetWingspan(double value) { + _listener.beforeSet(this, WINGSPAN__PROP, value); + _wingspan = value; + _listener.afterChanged(this, WINGSPAN__PROP); + } + + @Override + public test.openworld.deep.base.Bird setName(String value) { + internalSetName(value); + return this; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WINGSPAN__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WINGSPAN__PROP: return getWingspan(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WINGSPAN__PROP: internalSetWingspan((double) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WINGSPAN__PROP); + out.value(getWingspan()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WINGSPAN__PROP: setWingspan(in.nextDouble()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Bird} type. */ + public static final String BIRD__XML_ELEMENT = "bird"; + + /** XML attribute or element name of a {@link #getWingspan} property. */ + private static final String WINGSPAN__XML_ATTR = "wingspan"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WINGSPAN__XML_ATTR, Double.toString(getWingspan())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Bird} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Bird_Impl readBird_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case Sparrow_Impl.SPARROW__XML_ELEMENT: { + return test.openworld.deep.base.impl.Sparrow_Impl.readSparrow_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.XML_REGISTRY.get(in.getLocalName()); + test.openworld.deep.base.Animal instance = factory == null ? null : factory.create(); + if (instance instanceof Bird_Impl) { + Bird_Impl result = (Bird_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WINGSPAN__XML_ATTR: { + setWingspan(Double.parseDouble(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WINGSPAN__XML_ATTR: { + setWingspan(Double.parseDouble(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.openworld.deep.base.Animal.Visitor v, A arg) throws E { + return visit((test.openworld.deep.base.Bird.Visitor) v, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Dog_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Dog_Impl.java new file mode 100644 index 00000000..6de0269c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Dog_Impl.java @@ -0,0 +1,178 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Dog}. + */ +public class Dog_Impl extends test.openworld.deep.base.impl.Animal_Impl implements test.openworld.deep.base.Dog { + + private boolean _good = false; + + /** + * Creates a {@link Dog_Impl} instance. + * + * @see test.openworld.deep.base.Dog#create() + */ + public Dog_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.DOG; + } + + @Override + public final boolean isGood() { + return _good; + } + + @Override + public test.openworld.deep.base.Dog setGood(boolean value) { + internalSetGood(value); + return this; + } + + /** Internal setter for {@link #isGood()} without chain call utility. */ + protected final void internalSetGood(boolean value) { + _listener.beforeSet(this, GOOD__PROP, value); + _good = value; + _listener.afterChanged(this, GOOD__PROP); + } + + @Override + public test.openworld.deep.base.Dog setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return DOG__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + GOOD__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case GOOD__PROP: return isGood(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case GOOD__PROP: internalSetGood((boolean) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(GOOD__PROP); + out.value(isGood()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case GOOD__PROP: setGood(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Dog} type. */ + public static final String DOG__XML_ELEMENT = "dog"; + + /** XML attribute or element name of a {@link #isGood} property. */ + private static final String GOOD__XML_ATTR = "good"; + + @Override + public String getXmlTagName() { + return DOG__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(GOOD__XML_ATTR, Boolean.toString(isGood())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Dog} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Dog_Impl readDog_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Dog_Impl result = new Dog_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case GOOD__XML_ATTR: { + setGood(Boolean.parseBoolean(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case GOOD__XML_ATTR: { + setGood(Boolean.parseBoolean(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.base.Animal.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Habitat_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Habitat_Impl.java new file mode 100644 index 00000000..83a520e3 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Habitat_Impl.java @@ -0,0 +1,797 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Habitat}. + */ +public class Habitat_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.base.Habitat { + /** + * Implementation of {@link test.openworld.deep.base.Habitat.Plant}. + */ + public static abstract class Plant_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.base.Habitat.Plant { + + static { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + } + + private String _species = ""; + + /** + * Creates a {@link Plant_Impl} instance. + */ + public Plant_Impl() { + super(); + } + + @Override + public final String getSpecies() { + return _species; + } + + @Override + public test.openworld.deep.base.Habitat.Plant setSpecies(String value) { + internalSetSpecies(value); + return this; + } + + /** Internal setter for {@link #getSpecies()} without chain call utility. */ + protected final void internalSetSpecies(String value) { + _listener.beforeSet(this, SPECIES__PROP, value); + _species = value; + _listener.afterChanged(this, SPECIES__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.base.Habitat.Plant registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.base.Habitat.Plant unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SPECIES__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SPECIES__PROP: return getSpecies(); + default: return test.openworld.deep.base.Habitat.Plant.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SPECIES__PROP: internalSetSpecies((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SPECIES__PROP); + out.value(getSpecies()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SPECIES__PROP: setSpecies(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Habitat.Plant} type. */ + public static final String PLANT__XML_ELEMENT = "plant"; + + /** XML attribute or element name of a {@link #getSpecies} property. */ + private static final String SPECIES__XML_ATTR = "species"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(SPECIES__XML_ATTR, getSpecies()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Habitat.Plant} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Plant_Impl readPlant_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl.BIRCH__XML_ELEMENT: { + return test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl.readBirch_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Habitat.Plant.XML_REGISTRY.get(in.getLocalName()); + test.openworld.deep.base.Habitat.Plant instance = factory == null ? null : factory.create(); + if (instance instanceof Plant_Impl) { + Plant_Impl result = (Plant_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case SPECIES__XML_ATTR: { + setSpecies(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SPECIES__XML_ATTR: { + setSpecies(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + } + /** + * Implementation of {@link test.openworld.deep.base.Habitat.Tree}. + */ + public static abstract class Tree_Impl extends test.openworld.deep.base.impl.Habitat_Impl.Plant_Impl implements test.openworld.deep.base.Habitat.Tree { + + private int _height = 0; + + /** + * Creates a {@link Tree_Impl} instance. + */ + public Tree_Impl() { + super(); + } + + @Override + public final int getHeight() { + return _height; + } + + @Override + public test.openworld.deep.base.Habitat.Tree setHeight(int value) { + internalSetHeight(value); + return this; + } + + /** Internal setter for {@link #getHeight()} without chain call utility. */ + protected final void internalSetHeight(int value) { + _listener.beforeSet(this, HEIGHT__PROP, value); + _height = value; + _listener.afterChanged(this, HEIGHT__PROP); + } + + @Override + public test.openworld.deep.base.Habitat.Tree setSpecies(String value) { + internalSetSpecies(value); + return this; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + HEIGHT__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Habitat_Impl.Plant_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Habitat_Impl.Plant_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case HEIGHT__PROP: return getHeight(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case HEIGHT__PROP: internalSetHeight((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(HEIGHT__PROP); + out.value(getHeight()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case HEIGHT__PROP: setHeight(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Habitat.Tree} type. */ + public static final String TREE__XML_ELEMENT = "tree"; + + /** XML attribute or element name of a {@link #getHeight} property. */ + private static final String HEIGHT__XML_ATTR = "height"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(HEIGHT__XML_ATTR, Integer.toString(getHeight())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Habitat.Tree} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Tree_Impl readTree_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl.BIRCH__XML_ELEMENT: { + return test.openworld.deep.base.impl.Habitat_Impl.Birch_Impl.readBirch_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Habitat.Plant.XML_REGISTRY.get(in.getLocalName()); + test.openworld.deep.base.Habitat.Plant instance = factory == null ? null : factory.create(); + if (instance instanceof Tree_Impl) { + Tree_Impl result = (Tree_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case HEIGHT__XML_ATTR: { + setHeight(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case HEIGHT__XML_ATTR: { + setHeight(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.openworld.deep.base.Habitat.Plant.Visitor v, A arg) throws E { + return visit((test.openworld.deep.base.Habitat.Tree.Visitor) v, arg); + } + + } + /** + * Implementation of {@link test.openworld.deep.base.Habitat.Birch}. + */ + public static class Birch_Impl extends test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl implements test.openworld.deep.base.Habitat.Birch { + + /** + * Creates a {@link Birch_Impl} instance. + * + * @see test.openworld.deep.base.Habitat.Birch#create() + */ + public Birch_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.BIRCH; + } + + @Override + public test.openworld.deep.base.Habitat.Birch setHeight(int value) { + internalSetHeight(value); + return this; + } + + @Override + public test.openworld.deep.base.Habitat.Birch setSpecies(String value) { + internalSetSpecies(value); + return this; + } + + @Override + public String jsonType() { + return BIRCH__TYPE; + } + + /** XML element name representing a {@link test.openworld.deep.base.Habitat.Birch} type. */ + public static final String BIRCH__XML_ELEMENT = "birch"; + + @Override + public String getXmlTagName() { + return BIRCH__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Habitat.Birch} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Birch_Impl readBirch_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Birch_Impl result = new Birch_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.base.Habitat.Tree.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + + } + + private test.openworld.deep.base.Habitat.Tree _tallest = null; + + private final java.util.List _plants = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.openworld.deep.base.Habitat.Plant element) { + _listener.beforeAdd(Habitat_Impl.this, PLANTS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.openworld.deep.base.Habitat.Plant element) { + _listener.afterRemove(Habitat_Impl.this, PLANTS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Habitat_Impl.this, PLANTS__PROP); + } + }; + + /** + * Creates a {@link Habitat_Impl} instance. + * + * @see test.openworld.deep.base.Habitat#create() + */ + public Habitat_Impl() { + super(); + } + + @Override + public final test.openworld.deep.base.Habitat.Tree getTallest() { + return _tallest; + } + + @Override + public test.openworld.deep.base.Habitat setTallest(test.openworld.deep.base.Habitat.Tree value) { + internalSetTallest(value); + return this; + } + + /** Internal setter for {@link #getTallest()} without chain call utility. */ + protected final void internalSetTallest(test.openworld.deep.base.Habitat.Tree value) { + _listener.beforeSet(this, TALLEST__PROP, value); + _tallest = value; + _listener.afterChanged(this, TALLEST__PROP); + } + + @Override + public final boolean hasTallest() { + return _tallest != null; + } + + @Override + public final java.util.List getPlants() { + return _plants; + } + + @Override + public test.openworld.deep.base.Habitat setPlants(java.util.List value) { + internalSetPlants(value); + return this; + } + + /** Internal setter for {@link #getPlants()} without chain call utility. */ + protected final void internalSetPlants(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'plants' cannot be null."); + _plants.clear(); + _plants.addAll(value); + } + + @Override + public test.openworld.deep.base.Habitat addPlant(test.openworld.deep.base.Habitat.Plant value) { + internalAddPlant(value); + return this; + } + + /** Implementation of {@link #addPlant(test.openworld.deep.base.Habitat.Plant)} without chain call utility. */ + protected final void internalAddPlant(test.openworld.deep.base.Habitat.Plant value) { + _plants.add(value); + } + + @Override + public final void removePlant(test.openworld.deep.base.Habitat.Plant value) { + _plants.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.base.Habitat registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.base.Habitat unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return HABITAT__TYPE; + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TALLEST__PROP, + PLANTS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TALLEST__PROP: return getTallest(); + case PLANTS__PROP: return getPlants(); + default: return test.openworld.deep.base.Habitat.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TALLEST__PROP: internalSetTallest((test.openworld.deep.base.Habitat.Tree) value); break; + case PLANTS__PROP: internalSetPlants(de.haumacher.msgbuf.util.Conversions.asList(test.openworld.deep.base.Habitat.Plant.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasTallest()) { + out.name(TALLEST__PROP); + getTallest().writeTo(out); + } + out.name(PLANTS__PROP); + out.beginArray(); + for (test.openworld.deep.base.Habitat.Plant x : getPlants()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TALLEST__PROP: setTallest(test.openworld.deep.base.Habitat.Tree.readTree(in)); break; + case PLANTS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.openworld.deep.base.Habitat.Plant.readPlant(in)); + } + in.endArray(); + setPlants(newValue); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Habitat} type. */ + public static final String HABITAT__XML_ELEMENT = "habitat"; + + /** XML attribute or element name of a {@link #getTallest} property. */ + private static final String TALLEST__XML_ATTR = "tallest"; + + /** XML attribute or element name of a {@link #getPlants} property. */ + private static final String PLANTS__XML_ATTR = "plants"; + + @Override + public String getXmlTagName() { + return HABITAT__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasTallest()) { + out.writeStartElement(TALLEST__XML_ATTR); + getTallest().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(PLANTS__XML_ATTR); + for (test.openworld.deep.base.Habitat.Plant element : getPlants()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.openworld.deep.base.Habitat} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Habitat_Impl readHabitat_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Habitat_Impl result = new Habitat_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TALLEST__XML_ATTR: { + in.nextTag(); + setTallest(test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl.readTree_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case PLANTS__XML_ATTR: { + internalReadPlantsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadPlantsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addPlant(test.openworld.deep.base.impl.Habitat_Impl.Plant_Impl.readPlant_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Sparrow_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Sparrow_Impl.java new file mode 100644 index 00000000..9a70c959 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Sparrow_Impl.java @@ -0,0 +1,184 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Sparrow}. + */ +public class Sparrow_Impl extends test.openworld.deep.base.impl.Bird_Impl implements test.openworld.deep.base.Sparrow { + + private int _flock = 0; + + /** + * Creates a {@link Sparrow_Impl} instance. + * + * @see test.openworld.deep.base.Sparrow#create() + */ + public Sparrow_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.SPARROW; + } + + @Override + public final int getFlock() { + return _flock; + } + + @Override + public test.openworld.deep.base.Sparrow setFlock(int value) { + internalSetFlock(value); + return this; + } + + /** Internal setter for {@link #getFlock()} without chain call utility. */ + protected final void internalSetFlock(int value) { + _listener.beforeSet(this, FLOCK__PROP, value); + _flock = value; + _listener.afterChanged(this, FLOCK__PROP); + } + + @Override + public test.openworld.deep.base.Sparrow setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + @Override + public test.openworld.deep.base.Sparrow setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return SPARROW__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + FLOCK__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case FLOCK__PROP: return getFlock(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case FLOCK__PROP: internalSetFlock((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(FLOCK__PROP); + out.value(getFlock()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case FLOCK__PROP: setFlock(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Sparrow} type. */ + public static final String SPARROW__XML_ELEMENT = "sparrow"; + + /** XML attribute or element name of a {@link #getFlock} property. */ + private static final String FLOCK__XML_ATTR = "flock"; + + @Override + public String getXmlTagName() { + return SPARROW__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(FLOCK__XML_ATTR, Integer.toString(getFlock())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.base.Sparrow} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Sparrow_Impl readSparrow_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Sparrow_Impl result = new Sparrow_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case FLOCK__XML_ATTR: { + setFlock(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case FLOCK__XML_ATTR: { + setFlock(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.base.Bird.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Zoo_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Zoo_Impl.java new file mode 100644 index 00000000..b794e689 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/base/impl/Zoo_Impl.java @@ -0,0 +1,813 @@ +package test.openworld.deep.base.impl; + +/** + * Implementation of {@link test.openworld.deep.base.Zoo}. + */ +public class Zoo_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.base.Zoo { + /** + * Implementation of {@link test.openworld.deep.base.Zoo.Aviary}. + */ + public static class Aviary_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.base.Zoo.Aviary { + + private test.openworld.deep.base.Bird _boss = null; + + private final java.util.List _residents = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.openworld.deep.base.Bird element) { + _listener.beforeAdd(Aviary_Impl.this, RESIDENTS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.openworld.deep.base.Bird element) { + _listener.afterRemove(Aviary_Impl.this, RESIDENTS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Aviary_Impl.this, RESIDENTS__PROP); + } + }; + + /** + * Creates a {@link Aviary_Impl} instance. + * + * @see test.openworld.deep.base.Zoo.Aviary#create() + */ + public Aviary_Impl() { + super(); + } + + @Override + public final test.openworld.deep.base.Bird getBoss() { + return _boss; + } + + @Override + public test.openworld.deep.base.Zoo.Aviary setBoss(test.openworld.deep.base.Bird value) { + internalSetBoss(value); + return this; + } + + /** Internal setter for {@link #getBoss()} without chain call utility. */ + protected final void internalSetBoss(test.openworld.deep.base.Bird value) { + _listener.beforeSet(this, BOSS__PROP, value); + _boss = value; + _listener.afterChanged(this, BOSS__PROP); + } + + @Override + public final boolean hasBoss() { + return _boss != null; + } + + @Override + public final java.util.List getResidents() { + return _residents; + } + + @Override + public test.openworld.deep.base.Zoo.Aviary setResidents(java.util.List value) { + internalSetResidents(value); + return this; + } + + /** Internal setter for {@link #getResidents()} without chain call utility. */ + protected final void internalSetResidents(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'residents' cannot be null."); + _residents.clear(); + _residents.addAll(value); + } + + @Override + public test.openworld.deep.base.Zoo.Aviary addResident(test.openworld.deep.base.Bird value) { + internalAddResident(value); + return this; + } + + /** Implementation of {@link #addResident(test.openworld.deep.base.Bird)} without chain call utility. */ + protected final void internalAddResident(test.openworld.deep.base.Bird value) { + _residents.add(value); + } + + @Override + public final void removeResident(test.openworld.deep.base.Bird value) { + _residents.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.base.Zoo.Aviary registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.base.Zoo.Aviary unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return AVIARY__TYPE; + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + BOSS__PROP, + RESIDENTS__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case BOSS__PROP: return getBoss(); + case RESIDENTS__PROP: return getResidents(); + default: return test.openworld.deep.base.Zoo.Aviary.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case BOSS__PROP: internalSetBoss((test.openworld.deep.base.Bird) value); break; + case RESIDENTS__PROP: internalSetResidents(de.haumacher.msgbuf.util.Conversions.asList(test.openworld.deep.base.Bird.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasBoss()) { + out.name(BOSS__PROP); + getBoss().writeTo(out); + } + out.name(RESIDENTS__PROP); + out.beginArray(); + for (test.openworld.deep.base.Bird x : getResidents()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case BOSS__PROP: setBoss(test.openworld.deep.base.Bird.readBird(in)); break; + case RESIDENTS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.openworld.deep.base.Bird.readBird(in)); + } + in.endArray(); + setResidents(newValue); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Zoo.Aviary} type. */ + public static final String AVIARY__XML_ELEMENT = "aviary"; + + /** XML attribute or element name of a {@link #getBoss} property. */ + private static final String BOSS__XML_ATTR = "boss"; + + /** XML attribute or element name of a {@link #getResidents} property. */ + private static final String RESIDENTS__XML_ATTR = "residents"; + + @Override + public String getXmlTagName() { + return AVIARY__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasBoss()) { + out.writeStartElement(BOSS__XML_ATTR); + getBoss().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(RESIDENTS__XML_ATTR); + for (test.openworld.deep.base.Bird element : getResidents()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.openworld.deep.base.Zoo.Aviary} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Aviary_Impl readAviary_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Aviary_Impl result = new Aviary_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case BOSS__XML_ATTR: { + in.nextTag(); + setBoss(test.openworld.deep.base.impl.Bird_Impl.readBird_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case RESIDENTS__XML_ATTR: { + internalReadResidentsListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadResidentsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addResident(test.openworld.deep.base.impl.Bird_Impl.readBird_XmlContent(in)); + } + } + + } + + private test.openworld.deep.base.Animal _star = null; + + private final java.util.List _animals = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.openworld.deep.base.Animal element) { + _listener.beforeAdd(Zoo_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.openworld.deep.base.Animal element) { + _listener.afterRemove(Zoo_Impl.this, ANIMALS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Zoo_Impl.this, ANIMALS__PROP); + } + }; + + private test.openworld.deep.base.Bird _favorite = null; + + private final java.util.List _birds = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.openworld.deep.base.Bird element) { + _listener.beforeAdd(Zoo_Impl.this, BIRDS__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.openworld.deep.base.Bird element) { + _listener.afterRemove(Zoo_Impl.this, BIRDS__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Zoo_Impl.this, BIRDS__PROP); + } + }; + + private test.openworld.deep.base.Zoo.Aviary _aviary = null; + + /** + * Creates a {@link Zoo_Impl} instance. + * + * @see test.openworld.deep.base.Zoo#create() + */ + public Zoo_Impl() { + super(); + } + + @Override + public final test.openworld.deep.base.Animal getStar() { + return _star; + } + + @Override + public test.openworld.deep.base.Zoo setStar(test.openworld.deep.base.Animal value) { + internalSetStar(value); + return this; + } + + /** Internal setter for {@link #getStar()} without chain call utility. */ + protected final void internalSetStar(test.openworld.deep.base.Animal value) { + _listener.beforeSet(this, STAR__PROP, value); + _star = value; + _listener.afterChanged(this, STAR__PROP); + } + + @Override + public final boolean hasStar() { + return _star != null; + } + + @Override + public final java.util.List getAnimals() { + return _animals; + } + + @Override + public test.openworld.deep.base.Zoo setAnimals(java.util.List value) { + internalSetAnimals(value); + return this; + } + + /** Internal setter for {@link #getAnimals()} without chain call utility. */ + protected final void internalSetAnimals(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'animals' cannot be null."); + _animals.clear(); + _animals.addAll(value); + } + + @Override + public test.openworld.deep.base.Zoo addAnimal(test.openworld.deep.base.Animal value) { + internalAddAnimal(value); + return this; + } + + /** Implementation of {@link #addAnimal(test.openworld.deep.base.Animal)} without chain call utility. */ + protected final void internalAddAnimal(test.openworld.deep.base.Animal value) { + _animals.add(value); + } + + @Override + public final void removeAnimal(test.openworld.deep.base.Animal value) { + _animals.remove(value); + } + + @Override + public final test.openworld.deep.base.Bird getFavorite() { + return _favorite; + } + + @Override + public test.openworld.deep.base.Zoo setFavorite(test.openworld.deep.base.Bird value) { + internalSetFavorite(value); + return this; + } + + /** Internal setter for {@link #getFavorite()} without chain call utility. */ + protected final void internalSetFavorite(test.openworld.deep.base.Bird value) { + _listener.beforeSet(this, FAVORITE__PROP, value); + _favorite = value; + _listener.afterChanged(this, FAVORITE__PROP); + } + + @Override + public final boolean hasFavorite() { + return _favorite != null; + } + + @Override + public final java.util.List getBirds() { + return _birds; + } + + @Override + public test.openworld.deep.base.Zoo setBirds(java.util.List value) { + internalSetBirds(value); + return this; + } + + /** Internal setter for {@link #getBirds()} without chain call utility. */ + protected final void internalSetBirds(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'birds' cannot be null."); + _birds.clear(); + _birds.addAll(value); + } + + @Override + public test.openworld.deep.base.Zoo addBird(test.openworld.deep.base.Bird value) { + internalAddBird(value); + return this; + } + + /** Implementation of {@link #addBird(test.openworld.deep.base.Bird)} without chain call utility. */ + protected final void internalAddBird(test.openworld.deep.base.Bird value) { + _birds.add(value); + } + + @Override + public final void removeBird(test.openworld.deep.base.Bird value) { + _birds.remove(value); + } + + @Override + public final test.openworld.deep.base.Zoo.Aviary getAviary() { + return _aviary; + } + + @Override + public test.openworld.deep.base.Zoo setAviary(test.openworld.deep.base.Zoo.Aviary value) { + internalSetAviary(value); + return this; + } + + /** Internal setter for {@link #getAviary()} without chain call utility. */ + protected final void internalSetAviary(test.openworld.deep.base.Zoo.Aviary value) { + _listener.beforeSet(this, AVIARY__PROP, value); + _aviary = value; + _listener.afterChanged(this, AVIARY__PROP); + } + + @Override + public final boolean hasAviary() { + return _aviary != null; + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.base.Zoo registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.base.Zoo unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return ZOO__TYPE; + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + STAR__PROP, + ANIMALS__PROP, + FAVORITE__PROP, + BIRDS__PROP, + AVIARY__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case STAR__PROP: return getStar(); + case ANIMALS__PROP: return getAnimals(); + case FAVORITE__PROP: return getFavorite(); + case BIRDS__PROP: return getBirds(); + case AVIARY__PROP: return getAviary(); + default: return test.openworld.deep.base.Zoo.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case STAR__PROP: internalSetStar((test.openworld.deep.base.Animal) value); break; + case ANIMALS__PROP: internalSetAnimals(de.haumacher.msgbuf.util.Conversions.asList(test.openworld.deep.base.Animal.class, value)); break; + case FAVORITE__PROP: internalSetFavorite((test.openworld.deep.base.Bird) value); break; + case BIRDS__PROP: internalSetBirds(de.haumacher.msgbuf.util.Conversions.asList(test.openworld.deep.base.Bird.class, value)); break; + case AVIARY__PROP: internalSetAviary((test.openworld.deep.base.Zoo.Aviary) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasStar()) { + out.name(STAR__PROP); + getStar().writeTo(out); + } + out.name(ANIMALS__PROP); + out.beginArray(); + for (test.openworld.deep.base.Animal x : getAnimals()) { + x.writeTo(out); + } + out.endArray(); + if (hasFavorite()) { + out.name(FAVORITE__PROP); + getFavorite().writeTo(out); + } + out.name(BIRDS__PROP); + out.beginArray(); + for (test.openworld.deep.base.Bird x : getBirds()) { + x.writeTo(out); + } + out.endArray(); + if (hasAviary()) { + out.name(AVIARY__PROP); + getAviary().writeTo(out); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case STAR__PROP: setStar(test.openworld.deep.base.Animal.readAnimal(in)); break; + case ANIMALS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.openworld.deep.base.Animal.readAnimal(in)); + } + in.endArray(); + setAnimals(newValue); + } + break; + case FAVORITE__PROP: setFavorite(test.openworld.deep.base.Bird.readBird(in)); break; + case BIRDS__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.openworld.deep.base.Bird.readBird(in)); + } + in.endArray(); + setBirds(newValue); + } + break; + case AVIARY__PROP: setAviary(test.openworld.deep.base.Zoo.Aviary.readAviary(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.base.Zoo} type. */ + public static final String ZOO__XML_ELEMENT = "zoo"; + + /** XML attribute or element name of a {@link #getStar} property. */ + private static final String STAR__XML_ATTR = "star"; + + /** XML attribute or element name of a {@link #getAnimals} property. */ + private static final String ANIMALS__XML_ATTR = "animals"; + + /** XML attribute or element name of a {@link #getFavorite} property. */ + private static final String FAVORITE__XML_ATTR = "favorite"; + + /** XML attribute or element name of a {@link #getBirds} property. */ + private static final String BIRDS__XML_ATTR = "birds"; + + /** XML attribute or element name of a {@link #getAviary} property. */ + private static final String AVIARY__XML_ATTR = "aviary"; + + @Override + public String getXmlTagName() { + return ZOO__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasStar()) { + out.writeStartElement(STAR__XML_ATTR); + getStar().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(ANIMALS__XML_ATTR); + for (test.openworld.deep.base.Animal element : getAnimals()) { + element.writeTo(out); + } + out.writeEndElement(); + if (hasFavorite()) { + out.writeStartElement(FAVORITE__XML_ATTR); + getFavorite().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(BIRDS__XML_ATTR); + for (test.openworld.deep.base.Bird element : getBirds()) { + element.writeTo(out); + } + out.writeEndElement(); + if (hasAviary()) { + out.writeStartElement(AVIARY__XML_ATTR); + getAviary().writeContent(out); + out.writeEndElement(); + } + } + + /** Creates a new {@link test.openworld.deep.base.Zoo} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Zoo_Impl readZoo_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Zoo_Impl result = new Zoo_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case STAR__XML_ATTR: { + in.nextTag(); + setStar(test.openworld.deep.base.impl.Animal_Impl.readAnimal_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case ANIMALS__XML_ATTR: { + internalReadAnimalsListXml(in); + break; + } + case FAVORITE__XML_ATTR: { + in.nextTag(); + setFavorite(test.openworld.deep.base.impl.Bird_Impl.readBird_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case BIRDS__XML_ATTR: { + internalReadBirdsListXml(in); + break; + } + case AVIARY__XML_ATTR: { + setAviary(test.openworld.deep.base.impl.Zoo_Impl.Aviary_Impl.readAviary_XmlContent(in)); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadAnimalsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addAnimal(test.openworld.deep.base.impl.Animal_Impl.readAnimal_XmlContent(in)); + } + } + + private void internalReadBirdsListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addBird(test.openworld.deep.base.impl.Bird_Impl.readBird_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Ext1Types.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Ext1Types.java new file mode 100644 index 00000000..2d9532fe --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Ext1Types.java @@ -0,0 +1,24 @@ +package test.openworld.deep.ext1; + +/** + * Registration of extension types for the OpenWorld protocol. + */ +public class Ext1Types implements de.haumacher.msgbuf.data.TypeRegistration { + + @Override + public void register() { + test.openworld.deep.base.Animal.register(test.openworld.deep.ext1.Parrot.PARROT__TYPE, test.openworld.deep.ext1.Parrot::create); + test.openworld.deep.base.Animal.registerXml(test.openworld.deep.ext1.impl.Parrot_Impl.PARROT__XML_ELEMENT, test.openworld.deep.ext1.Parrot::create); + test.openworld.deep.base.Animal.register(test.openworld.deep.ext1.Trout.TROUT__TYPE, test.openworld.deep.ext1.Trout::create); + test.openworld.deep.base.Animal.registerXml(test.openworld.deep.ext1.impl.Trout_Impl.TROUT__XML_ELEMENT, test.openworld.deep.ext1.Trout::create); + test.openworld.deep.base.Habitat.Plant.register(test.openworld.deep.ext1.Forest.Oak.OAK__TYPE, test.openworld.deep.ext1.Forest.Oak::create); + test.openworld.deep.base.Habitat.Plant.registerXml(test.openworld.deep.ext1.impl.Forest_Impl.Oak_Impl.OAK__XML_ELEMENT, test.openworld.deep.ext1.Forest.Oak::create); + } + + /** + * Explicit initialization for GWT or manual use. + */ + public static void init() { + new Ext1Types().register(); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Fish.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Fish.java new file mode 100644 index 00000000..07a58f32 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Fish.java @@ -0,0 +1,65 @@ +package test.openworld.deep.ext1; + +/** + * Abstract intermediate declared in an extension file: a sibling subtree of Bird. + */ +public interface Fish extends test.openworld.deep.base.Animal { + + /** Visitor interface for the {@link test.openworld.deep.ext1.Fish} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.openworld.deep.ext1.Trout}.*/ + R visit(test.openworld.deep.ext1.Trout self, A arg) throws E; + + /** Fallback for visiting subtypes not known at compile time. */ + R visitDefault(test.openworld.deep.ext1.Fish self, A arg) throws E; + + } + + /** @see #getFins() */ + String FINS__PROP = "fins"; + + int getFins(); + + /** + * @see #getFins() + */ + test.openworld.deep.ext1.Fish setFins(int value); + + @Override + test.openworld.deep.ext1.Fish setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Fish readFish(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.Fish result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case Trout.TROUT__TYPE: result = test.openworld.deep.ext1.Trout.readTrout(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.REGISTRY.get(type); + test.openworld.deep.base.Animal instance = factory == null ? null : factory.create(); + if (instance instanceof test.openworld.deep.ext1.Fish) { + result = (test.openworld.deep.ext1.Fish) instance; + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Creates a new {@link Fish} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Fish readFish(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Fish_Impl.readFish_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Forest.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Forest.java new file mode 100644 index 00000000..78dcbcb4 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Forest.java @@ -0,0 +1,87 @@ +package test.openworld.deep.ext1; + +/** + * Nested leaf of a nested hierarchy of another file. + */ +public interface Forest extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + public interface Oak extends test.openworld.deep.base.Habitat.Tree { + + /** Extended visitor that can handle {@link Oak}. */ + public interface Visitor extends test.openworld.deep.base.Habitat.Tree.Visitor { + + /** Visit case for {@link Oak}. */ + R visit(test.openworld.deep.ext1.Forest.Oak self, A arg) throws E; + + } + + /** + * Creates a {@link test.openworld.deep.ext1.Forest.Oak} instance. + */ + static test.openworld.deep.ext1.Forest.Oak create() { + return new test.openworld.deep.ext1.impl.Forest_Impl.Oak_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext1.Forest.Oak} type in JSON format. */ + String OAK__TYPE = "Oak"; + + /** @see #getAge() */ + String AGE__PROP = "age"; + + int getAge(); + + /** + * @see #getAge() + */ + test.openworld.deep.ext1.Forest.Oak setAge(int value); + + @Override + test.openworld.deep.ext1.Forest.Oak setHeight(int value); + + @Override + test.openworld.deep.ext1.Forest.Oak setSpecies(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Forest.Oak readOak(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.impl.Forest_Impl.Oak_Impl result = new test.openworld.deep.ext1.impl.Forest_Impl.Oak_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Oak} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Oak readOak(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Forest_Impl.Oak_Impl.readOak_XmlContent(in); + } + + } + + /** + * Creates a {@link test.openworld.deep.ext1.Forest} instance. + */ + static test.openworld.deep.ext1.Forest create() { + return new test.openworld.deep.ext1.impl.Forest_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext1.Forest} type in JSON format. */ + String FOREST__TYPE = "Forest"; + + @Override + public test.openworld.deep.ext1.Forest registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.ext1.Forest unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Forest readForest(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.impl.Forest_Impl result = new test.openworld.deep.ext1.impl.Forest_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Forest} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Forest readForest(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Forest_Impl.readForest_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Parrot.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Parrot.java new file mode 100644 index 00000000..f45e9d51 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Parrot.java @@ -0,0 +1,55 @@ +package test.openworld.deep.ext1; + +/** + * Leaf of another file below an abstract intermediate of the base file. + */ +public interface Parrot extends test.openworld.deep.base.Bird { + + /** Extended visitor that can handle {@link Parrot}. */ + public interface Visitor extends test.openworld.deep.base.Bird.Visitor { + + /** Visit case for {@link Parrot}. */ + R visit(test.openworld.deep.ext1.Parrot self, A arg) throws E; + + } + + /** + * Creates a {@link test.openworld.deep.ext1.Parrot} instance. + */ + static test.openworld.deep.ext1.Parrot create() { + return new test.openworld.deep.ext1.impl.Parrot_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext1.Parrot} type in JSON format. */ + String PARROT__TYPE = "Parrot"; + + /** @see #getWord() */ + String WORD__PROP = "word"; + + String getWord(); + + /** + * @see #getWord() + */ + test.openworld.deep.ext1.Parrot setWord(String value); + + @Override + test.openworld.deep.ext1.Parrot setWingspan(double value); + + @Override + test.openworld.deep.ext1.Parrot setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Parrot readParrot(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.impl.Parrot_Impl result = new test.openworld.deep.ext1.impl.Parrot_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Parrot} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Parrot readParrot(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Parrot_Impl.readParrot_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Pond.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Pond.java new file mode 100644 index 00000000..70a86f9e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Pond.java @@ -0,0 +1,72 @@ +package test.openworld.deep.ext1; + +/** + * Holder of values of the intermediate of this file. + */ +public interface Pond extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.openworld.deep.ext1.Pond} instance. + */ + static test.openworld.deep.ext1.Pond create() { + return new test.openworld.deep.ext1.impl.Pond_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext1.Pond} type in JSON format. */ + String POND__TYPE = "Pond"; + + /** @see #getKing() */ + String KING__PROP = "king"; + + /** @see #getSchool() */ + String SCHOOL__PROP = "school"; + + test.openworld.deep.ext1.Fish getKing(); + + /** + * @see #getKing() + */ + test.openworld.deep.ext1.Pond setKing(test.openworld.deep.ext1.Fish value); + + /** + * Checks, whether {@link #getKing()} has a value. + */ + boolean hasKing(); + + java.util.List getSchool(); + + /** + * @see #getSchool() + */ + test.openworld.deep.ext1.Pond setSchool(java.util.List value); + + /** + * Adds a value to the {@link #getSchool()} list. + */ + test.openworld.deep.ext1.Pond addSchool(test.openworld.deep.ext1.Fish value); + + /** + * Removes a value from the {@link #getSchool()} list. + */ + void removeSchool(test.openworld.deep.ext1.Fish value); + + @Override + public test.openworld.deep.ext1.Pond registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.deep.ext1.Pond unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Pond readPond(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.impl.Pond_Impl result = new test.openworld.deep.ext1.impl.Pond_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Pond} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Pond readPond(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Pond_Impl.readPond_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Trout.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Trout.java new file mode 100644 index 00000000..ac26b47b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/Trout.java @@ -0,0 +1,47 @@ +package test.openworld.deep.ext1; + +/** + * Leaf of the extension file below its own intermediate. + */ +public interface Trout extends test.openworld.deep.ext1.Fish { + + /** + * Creates a {@link test.openworld.deep.ext1.Trout} instance. + */ + static test.openworld.deep.ext1.Trout create() { + return new test.openworld.deep.ext1.impl.Trout_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext1.Trout} type in JSON format. */ + String TROUT__TYPE = "Trout"; + + /** @see #isRainbow() */ + String RAINBOW__PROP = "rainbow"; + + boolean isRainbow(); + + /** + * @see #isRainbow() + */ + test.openworld.deep.ext1.Trout setRainbow(boolean value); + + @Override + test.openworld.deep.ext1.Trout setFins(int value); + + @Override + test.openworld.deep.ext1.Trout setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext1.Trout readTrout(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext1.impl.Trout_Impl result = new test.openworld.deep.ext1.impl.Trout_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Trout} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Trout readTrout(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext1.impl.Trout_Impl.readTrout_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/ext1.proto b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/ext1.proto new file mode 100644 index 00000000..8e15bcd9 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/ext1.proto @@ -0,0 +1,35 @@ +package test.openworld.deep.ext1; + +import "../base/base.proto"; + +/* Declares an abstract intermediate that is extended in another file. */ +option OpenWorld; + +/** Leaf of another file below an abstract intermediate of the base file. */ +message Parrot extends test.openworld.deep.base.Bird { + string word; +} + +/** Abstract intermediate declared in an extension file: a sibling subtree of Bird. */ +abstract message Fish extends test.openworld.deep.base.Animal { + int32 fins; +} + +/** Leaf of the extension file below its own intermediate. */ +message Trout extends Fish { + bool rainbow; +} + +/** Holder of values of the intermediate of this file. */ +message Pond { + Fish king; + + repeated Fish school; +} + +/** Nested leaf of a nested hierarchy of another file. */ +message Forest { + message Oak extends test.openworld.deep.base.Habitat.Tree { + int32 age; + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Fish_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Fish_Impl.java new file mode 100644 index 00000000..07f1d1d7 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Fish_Impl.java @@ -0,0 +1,178 @@ +package test.openworld.deep.ext1.impl; + +/** + * Implementation of {@link test.openworld.deep.ext1.Fish}. + */ +public abstract class Fish_Impl extends test.openworld.deep.base.impl.Animal_Impl implements test.openworld.deep.ext1.Fish { + + private int _fins = 0; + + /** + * Creates a {@link Fish_Impl} instance. + */ + public Fish_Impl() { + super(); + } + + @Override + public final int getFins() { + return _fins; + } + + @Override + public test.openworld.deep.ext1.Fish setFins(int value) { + internalSetFins(value); + return this; + } + + /** Internal setter for {@link #getFins()} without chain call utility. */ + protected final void internalSetFins(int value) { + _listener.beforeSet(this, FINS__PROP, value); + _fins = value; + _listener.afterChanged(this, FINS__PROP); + } + + @Override + public test.openworld.deep.ext1.Fish setName(String value) { + internalSetName(value); + return this; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + FINS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Animal_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case FINS__PROP: return getFins(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case FINS__PROP: internalSetFins((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(FINS__PROP); + out.value(getFins()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case FINS__PROP: setFins(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Fish} type. */ + public static final String FISH__XML_ELEMENT = "fish"; + + /** XML attribute or element name of a {@link #getFins} property. */ + private static final String FINS__XML_ATTR = "fins"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(FINS__XML_ATTR, Integer.toString(getFins())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext1.Fish} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Fish_Impl readFish_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case Trout_Impl.TROUT__XML_ELEMENT: { + return test.openworld.deep.ext1.impl.Trout_Impl.readTrout_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.deep.base.Animal.XML_REGISTRY.get(in.getLocalName()); + test.openworld.deep.base.Animal instance = factory == null ? null : factory.create(); + if (instance instanceof Fish_Impl) { + Fish_Impl result = (Fish_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case FINS__XML_ATTR: { + setFins(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case FINS__XML_ATTR: { + setFins(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.openworld.deep.base.Animal.Visitor v, A arg) throws E { + if (v instanceof test.openworld.deep.ext1.Fish.Visitor) { + return visit((test.openworld.deep.ext1.Fish.Visitor) v, arg); + } + return v.visitDefault(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Forest_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Forest_Impl.java new file mode 100644 index 00000000..22b72524 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Forest_Impl.java @@ -0,0 +1,312 @@ +package test.openworld.deep.ext1.impl; + +/** + * Implementation of {@link test.openworld.deep.ext1.Forest}. + */ +public class Forest_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.ext1.Forest { + /** + * Implementation of {@link test.openworld.deep.ext1.Forest.Oak}. + */ + public static class Oak_Impl extends test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl implements test.openworld.deep.ext1.Forest.Oak { + + private int _age = 0; + + /** + * Creates a {@link Oak_Impl} instance. + * + * @see test.openworld.deep.ext1.Forest.Oak#create() + */ + public Oak_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final int getAge() { + return _age; + } + + @Override + public test.openworld.deep.ext1.Forest.Oak setAge(int value) { + internalSetAge(value); + return this; + } + + /** Internal setter for {@link #getAge()} without chain call utility. */ + protected final void internalSetAge(int value) { + _listener.beforeSet(this, AGE__PROP, value); + _age = value; + _listener.afterChanged(this, AGE__PROP); + } + + @Override + public test.openworld.deep.ext1.Forest.Oak setHeight(int value) { + internalSetHeight(value); + return this; + } + + @Override + public test.openworld.deep.ext1.Forest.Oak setSpecies(String value) { + internalSetSpecies(value); + return this; + } + + @Override + public String jsonType() { + return OAK__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + AGE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Habitat_Impl.Tree_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case AGE__PROP: return getAge(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case AGE__PROP: internalSetAge((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(AGE__PROP); + out.value(getAge()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case AGE__PROP: setAge(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Forest.Oak} type. */ + public static final String OAK__XML_ELEMENT = "oak"; + + /** XML attribute or element name of a {@link #getAge} property. */ + private static final String AGE__XML_ATTR = "age"; + + @Override + public String getXmlTagName() { + return OAK__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(AGE__XML_ATTR, Integer.toString(getAge())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext1.Forest.Oak} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Oak_Impl readOak_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Oak_Impl result = new Oak_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case AGE__XML_ATTR: { + setAge(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case AGE__XML_ATTR: { + setAge(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.base.Habitat.Tree.Visitor v, A arg) throws E { + if (v instanceof test.openworld.deep.ext1.Forest.Oak.Visitor) { + return ((test.openworld.deep.ext1.Forest.Oak.Visitor) v).visit(this, arg); + } + return v.visitDefault(this, arg); + } + + } + + /** + * Creates a {@link Forest_Impl} instance. + * + * @see test.openworld.deep.ext1.Forest#create() + */ + public Forest_Impl() { + super(); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.ext1.Forest registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.ext1.Forest unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return FOREST__TYPE; + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Forest} type. */ + public static final String FOREST__XML_ELEMENT = "forest"; + + @Override + public String getXmlTagName() { + return FOREST__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext1.Forest} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Forest_Impl readForest_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Forest_Impl result = new Forest_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Parrot_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Parrot_Impl.java new file mode 100644 index 00000000..dea0636b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Parrot_Impl.java @@ -0,0 +1,187 @@ +package test.openworld.deep.ext1.impl; + +/** + * Implementation of {@link test.openworld.deep.ext1.Parrot}. + */ +public class Parrot_Impl extends test.openworld.deep.base.impl.Bird_Impl implements test.openworld.deep.ext1.Parrot { + + private String _word = ""; + + /** + * Creates a {@link Parrot_Impl} instance. + * + * @see test.openworld.deep.ext1.Parrot#create() + */ + public Parrot_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final String getWord() { + return _word; + } + + @Override + public test.openworld.deep.ext1.Parrot setWord(String value) { + internalSetWord(value); + return this; + } + + /** Internal setter for {@link #getWord()} without chain call utility. */ + protected final void internalSetWord(String value) { + _listener.beforeSet(this, WORD__PROP, value); + _word = value; + _listener.afterChanged(this, WORD__PROP); + } + + @Override + public test.openworld.deep.ext1.Parrot setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + @Override + public test.openworld.deep.ext1.Parrot setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return PARROT__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + WORD__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case WORD__PROP: return getWord(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case WORD__PROP: internalSetWord((String) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(WORD__PROP); + out.value(getWord()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case WORD__PROP: setWord(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Parrot} type. */ + public static final String PARROT__XML_ELEMENT = "parrot"; + + /** XML attribute or element name of a {@link #getWord} property. */ + private static final String WORD__XML_ATTR = "word"; + + @Override + public String getXmlTagName() { + return PARROT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(WORD__XML_ATTR, getWord()); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext1.Parrot} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Parrot_Impl readParrot_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Parrot_Impl result = new Parrot_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case WORD__XML_ATTR: { + setWord(value); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case WORD__XML_ATTR: { + setWord(in.getElementText()); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.base.Bird.Visitor v, A arg) throws E { + if (v instanceof test.openworld.deep.ext1.Parrot.Visitor) { + return ((test.openworld.deep.ext1.Parrot.Visitor) v).visit(this, arg); + } + return v.visitDefault(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Pond_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Pond_Impl.java new file mode 100644 index 00000000..4c35571d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Pond_Impl.java @@ -0,0 +1,315 @@ +package test.openworld.deep.ext1.impl; + +/** + * Implementation of {@link test.openworld.deep.ext1.Pond}. + */ +public class Pond_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.deep.ext1.Pond { + + private test.openworld.deep.ext1.Fish _king = null; + + private final java.util.List _school = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.openworld.deep.ext1.Fish element) { + _listener.beforeAdd(Pond_Impl.this, SCHOOL__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.openworld.deep.ext1.Fish element) { + _listener.afterRemove(Pond_Impl.this, SCHOOL__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Pond_Impl.this, SCHOOL__PROP); + } + }; + + /** + * Creates a {@link Pond_Impl} instance. + * + * @see test.openworld.deep.ext1.Pond#create() + */ + public Pond_Impl() { + super(); + } + + @Override + public final test.openworld.deep.ext1.Fish getKing() { + return _king; + } + + @Override + public test.openworld.deep.ext1.Pond setKing(test.openworld.deep.ext1.Fish value) { + internalSetKing(value); + return this; + } + + /** Internal setter for {@link #getKing()} without chain call utility. */ + protected final void internalSetKing(test.openworld.deep.ext1.Fish value) { + _listener.beforeSet(this, KING__PROP, value); + _king = value; + _listener.afterChanged(this, KING__PROP); + } + + @Override + public final boolean hasKing() { + return _king != null; + } + + @Override + public final java.util.List getSchool() { + return _school; + } + + @Override + public test.openworld.deep.ext1.Pond setSchool(java.util.List value) { + internalSetSchool(value); + return this; + } + + /** Internal setter for {@link #getSchool()} without chain call utility. */ + protected final void internalSetSchool(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'school' cannot be null."); + _school.clear(); + _school.addAll(value); + } + + @Override + public test.openworld.deep.ext1.Pond addSchool(test.openworld.deep.ext1.Fish value) { + internalAddSchool(value); + return this; + } + + /** Implementation of {@link #addSchool(test.openworld.deep.ext1.Fish)} without chain call utility. */ + protected final void internalAddSchool(test.openworld.deep.ext1.Fish value) { + _school.add(value); + } + + @Override + public final void removeSchool(test.openworld.deep.ext1.Fish value) { + _school.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.deep.ext1.Pond registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.deep.ext1.Pond unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return POND__TYPE; + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + KING__PROP, + SCHOOL__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case KING__PROP: return getKing(); + case SCHOOL__PROP: return getSchool(); + default: return test.openworld.deep.ext1.Pond.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case KING__PROP: internalSetKing((test.openworld.deep.ext1.Fish) value); break; + case SCHOOL__PROP: internalSetSchool(de.haumacher.msgbuf.util.Conversions.asList(test.openworld.deep.ext1.Fish.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasKing()) { + out.name(KING__PROP); + getKing().writeTo(out); + } + out.name(SCHOOL__PROP); + out.beginArray(); + for (test.openworld.deep.ext1.Fish x : getSchool()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case KING__PROP: setKing(test.openworld.deep.ext1.Fish.readFish(in)); break; + case SCHOOL__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.openworld.deep.ext1.Fish.readFish(in)); + } + in.endArray(); + setSchool(newValue); + } + break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Pond} type. */ + public static final String POND__XML_ELEMENT = "pond"; + + /** XML attribute or element name of a {@link #getKing} property. */ + private static final String KING__XML_ATTR = "king"; + + /** XML attribute or element name of a {@link #getSchool} property. */ + private static final String SCHOOL__XML_ATTR = "school"; + + @Override + public String getXmlTagName() { + return POND__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasKing()) { + out.writeStartElement(KING__XML_ATTR); + getKing().writeTo(out); + out.writeEndElement(); + } + out.writeStartElement(SCHOOL__XML_ATTR); + for (test.openworld.deep.ext1.Fish element : getSchool()) { + element.writeTo(out); + } + out.writeEndElement(); + } + + /** Creates a new {@link test.openworld.deep.ext1.Pond} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Pond_Impl readPond_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Pond_Impl result = new Pond_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case KING__XML_ATTR: { + in.nextTag(); + setKing(test.openworld.deep.ext1.impl.Fish_Impl.readFish_XmlContent(in)); + internalSkipUntilMatchingEndElement(in); + break; + } + case SCHOOL__XML_ATTR: { + internalReadSchoolListXml(in); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + + private void internalReadSchoolListXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + + addSchool(test.openworld.deep.ext1.impl.Fish_Impl.readFish_XmlContent(in)); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Trout_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Trout_Impl.java new file mode 100644 index 00000000..493eaf7e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext1/impl/Trout_Impl.java @@ -0,0 +1,184 @@ +package test.openworld.deep.ext1.impl; + +/** + * Implementation of {@link test.openworld.deep.ext1.Trout}. + */ +public class Trout_Impl extends test.openworld.deep.ext1.impl.Fish_Impl implements test.openworld.deep.ext1.Trout { + + private boolean _rainbow = false; + + /** + * Creates a {@link Trout_Impl} instance. + * + * @see test.openworld.deep.ext1.Trout#create() + */ + public Trout_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final boolean isRainbow() { + return _rainbow; + } + + @Override + public test.openworld.deep.ext1.Trout setRainbow(boolean value) { + internalSetRainbow(value); + return this; + } + + /** Internal setter for {@link #isRainbow()} without chain call utility. */ + protected final void internalSetRainbow(boolean value) { + _listener.beforeSet(this, RAINBOW__PROP, value); + _rainbow = value; + _listener.afterChanged(this, RAINBOW__PROP); + } + + @Override + public test.openworld.deep.ext1.Trout setFins(int value) { + internalSetFins(value); + return this; + } + + @Override + public test.openworld.deep.ext1.Trout setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return TROUT__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + RAINBOW__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.ext1.impl.Fish_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.ext1.impl.Fish_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case RAINBOW__PROP: return isRainbow(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case RAINBOW__PROP: internalSetRainbow((boolean) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(RAINBOW__PROP); + out.value(isRainbow()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case RAINBOW__PROP: setRainbow(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext1.Trout} type. */ + public static final String TROUT__XML_ELEMENT = "trout"; + + /** XML attribute or element name of a {@link #isRainbow} property. */ + private static final String RAINBOW__XML_ATTR = "rainbow"; + + @Override + public String getXmlTagName() { + return TROUT__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(RAINBOW__XML_ATTR, Boolean.toString(isRainbow())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext1.Trout} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Trout_Impl readTrout_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Trout_Impl result = new Trout_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case RAINBOW__XML_ATTR: { + setRainbow(Boolean.parseBoolean(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case RAINBOW__XML_ATTR: { + setRainbow(Boolean.parseBoolean(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.ext1.Fish.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Eagle.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Eagle.java new file mode 100644 index 00000000..b465b27c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Eagle.java @@ -0,0 +1,47 @@ +package test.openworld.deep.ext2; + +public interface Eagle extends test.openworld.deep.ext2.Raptor { + + /** + * Creates a {@link test.openworld.deep.ext2.Eagle} instance. + */ + static test.openworld.deep.ext2.Eagle create() { + return new test.openworld.deep.ext2.impl.Eagle_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext2.Eagle} type in JSON format. */ + String EAGLE__TYPE = "Eagle"; + + /** @see #isBald() */ + String BALD__PROP = "bald"; + + boolean isBald(); + + /** + * @see #isBald() + */ + test.openworld.deep.ext2.Eagle setBald(boolean value); + + @Override + test.openworld.deep.ext2.Eagle setSpeed(double value); + + @Override + test.openworld.deep.ext2.Eagle setWingspan(double value); + + @Override + test.openworld.deep.ext2.Eagle setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext2.Eagle readEagle(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext2.impl.Eagle_Impl result = new test.openworld.deep.ext2.impl.Eagle_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Eagle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Eagle readEagle(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext2.impl.Eagle_Impl.readEagle_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Ext2Types.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Ext2Types.java new file mode 100644 index 00000000..0a9ec540 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Ext2Types.java @@ -0,0 +1,22 @@ +package test.openworld.deep.ext2; + +/** + * Registration of extension types for the OpenWorld protocol. + */ +public class Ext2Types implements de.haumacher.msgbuf.data.TypeRegistration { + + @Override + public void register() { + test.openworld.deep.base.Animal.register(test.openworld.deep.ext2.Shark.SHARK__TYPE, test.openworld.deep.ext2.Shark::create); + test.openworld.deep.base.Animal.registerXml(test.openworld.deep.ext2.impl.Shark_Impl.SHARK__XML_ELEMENT, test.openworld.deep.ext2.Shark::create); + test.openworld.deep.base.Animal.register(test.openworld.deep.ext2.Eagle.EAGLE__TYPE, test.openworld.deep.ext2.Eagle::create); + test.openworld.deep.base.Animal.registerXml(test.openworld.deep.ext2.impl.Eagle_Impl.EAGLE__XML_ELEMENT, test.openworld.deep.ext2.Eagle::create); + } + + /** + * Explicit initialization for GWT or manual use. + */ + public static void init() { + new Ext2Types().register(); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Raptor.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Raptor.java new file mode 100644 index 00000000..8bcd80cf --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Raptor.java @@ -0,0 +1,54 @@ +package test.openworld.deep.ext2; + +/** + * Abstract intermediate at depth three, below the intermediate of the base file. + */ +public interface Raptor extends test.openworld.deep.base.Bird { + + /** Visitor interface for the {@link test.openworld.deep.ext2.Raptor} hierarchy.*/ + public interface Visitor { + + /** Visit case for {@link test.openworld.deep.ext2.Eagle}.*/ + R visit(test.openworld.deep.ext2.Eagle self, A arg) throws E; + + } + + /** @see #getSpeed() */ + String SPEED__PROP = "speed"; + + double getSpeed(); + + /** + * @see #getSpeed() + */ + test.openworld.deep.ext2.Raptor setSpeed(double value); + + @Override + test.openworld.deep.ext2.Raptor setWingspan(double value); + + @Override + test.openworld.deep.ext2.Raptor setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext2.Raptor readRaptor(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext2.Raptor result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case Eagle.EAGLE__TYPE: result = test.openworld.deep.ext2.Eagle.readEagle(in); break; + default: in.skipValue(); result = null; break; + } + in.endArray(); + return result; + } + + /** Creates a new {@link Raptor} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Raptor readRaptor(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext2.impl.Raptor_Impl.readRaptor_XmlContent(in); + } + + /** Accepts the given visitor. */ + public abstract R visit(Visitor v, A arg) throws E; + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Shark.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Shark.java new file mode 100644 index 00000000..b3e35136 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/Shark.java @@ -0,0 +1,55 @@ +package test.openworld.deep.ext2; + +/** + * Leaf of a second extension file below the intermediate of the first extension file. + */ +public interface Shark extends test.openworld.deep.ext1.Fish { + + /** Extended visitor that can handle {@link Shark}. */ + public interface Visitor extends test.openworld.deep.ext1.Fish.Visitor { + + /** Visit case for {@link Shark}. */ + R visit(test.openworld.deep.ext2.Shark self, A arg) throws E; + + } + + /** + * Creates a {@link test.openworld.deep.ext2.Shark} instance. + */ + static test.openworld.deep.ext2.Shark create() { + return new test.openworld.deep.ext2.impl.Shark_Impl(); + } + + /** Identifier for the {@link test.openworld.deep.ext2.Shark} type in JSON format. */ + String SHARK__TYPE = "Shark"; + + /** @see #getTeeth() */ + String TEETH__PROP = "teeth"; + + int getTeeth(); + + /** + * @see #getTeeth() + */ + test.openworld.deep.ext2.Shark setTeeth(int value); + + @Override + test.openworld.deep.ext2.Shark setFins(int value); + + @Override + test.openworld.deep.ext2.Shark setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.deep.ext2.Shark readShark(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.deep.ext2.impl.Shark_Impl result = new test.openworld.deep.ext2.impl.Shark_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Shark} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shark readShark(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.deep.ext2.impl.Shark_Impl.readShark_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/ext2.proto b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/ext2.proto new file mode 100644 index 00000000..a0f7709f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/ext2.proto @@ -0,0 +1,18 @@ +package test.openworld.deep.ext2; + +import "../base/base.proto"; +import "../ext1/ext1.proto"; + +/** Leaf of a second extension file below the intermediate of the first extension file. */ +message Shark extends test.openworld.deep.ext1.Fish { + int32 teeth; +} + +/** Abstract intermediate at depth three, below the intermediate of the base file. */ +abstract message Raptor extends test.openworld.deep.base.Bird { + double speed; +} + +message Eagle extends Raptor { + bool bald; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Eagle_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Eagle_Impl.java new file mode 100644 index 00000000..35191233 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Eagle_Impl.java @@ -0,0 +1,190 @@ +package test.openworld.deep.ext2.impl; + +/** + * Implementation of {@link test.openworld.deep.ext2.Eagle}. + */ +public class Eagle_Impl extends test.openworld.deep.ext2.impl.Raptor_Impl implements test.openworld.deep.ext2.Eagle { + + private boolean _bald = false; + + /** + * Creates a {@link Eagle_Impl} instance. + * + * @see test.openworld.deep.ext2.Eagle#create() + */ + public Eagle_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final boolean isBald() { + return _bald; + } + + @Override + public test.openworld.deep.ext2.Eagle setBald(boolean value) { + internalSetBald(value); + return this; + } + + /** Internal setter for {@link #isBald()} without chain call utility. */ + protected final void internalSetBald(boolean value) { + _listener.beforeSet(this, BALD__PROP, value); + _bald = value; + _listener.afterChanged(this, BALD__PROP); + } + + @Override + public test.openworld.deep.ext2.Eagle setSpeed(double value) { + internalSetSpeed(value); + return this; + } + + @Override + public test.openworld.deep.ext2.Eagle setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + @Override + public test.openworld.deep.ext2.Eagle setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return EAGLE__TYPE; + } + + @SuppressWarnings("hiding") + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + BALD__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.ext2.impl.Raptor_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.ext2.impl.Raptor_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case BALD__PROP: return isBald(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case BALD__PROP: internalSetBald((boolean) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(BALD__PROP); + out.value(isBald()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case BALD__PROP: setBald(in.nextBoolean()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext2.Eagle} type. */ + public static final String EAGLE__XML_ELEMENT = "eagle"; + + /** XML attribute or element name of a {@link #isBald} property. */ + private static final String BALD__XML_ATTR = "bald"; + + @Override + public String getXmlTagName() { + return EAGLE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(BALD__XML_ATTR, Boolean.toString(isBald())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext2.Eagle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Eagle_Impl readEagle_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Eagle_Impl result = new Eagle_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case BALD__XML_ATTR: { + setBald(Boolean.parseBoolean(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case BALD__XML_ATTR: { + setBald(Boolean.parseBoolean(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.ext2.Raptor.Visitor v, A arg) throws E { + return v.visit(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Raptor_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Raptor_Impl.java new file mode 100644 index 00000000..7f1bb9df --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Raptor_Impl.java @@ -0,0 +1,177 @@ +package test.openworld.deep.ext2.impl; + +/** + * Implementation of {@link test.openworld.deep.ext2.Raptor}. + */ +public abstract class Raptor_Impl extends test.openworld.deep.base.impl.Bird_Impl implements test.openworld.deep.ext2.Raptor { + + private double _speed = 0.0d; + + /** + * Creates a {@link Raptor_Impl} instance. + */ + public Raptor_Impl() { + super(); + } + + @Override + public final double getSpeed() { + return _speed; + } + + @Override + public test.openworld.deep.ext2.Raptor setSpeed(double value) { + internalSetSpeed(value); + return this; + } + + /** Internal setter for {@link #getSpeed()} without chain call utility. */ + protected final void internalSetSpeed(double value) { + _listener.beforeSet(this, SPEED__PROP, value); + _speed = value; + _listener.afterChanged(this, SPEED__PROP); + } + + @Override + public test.openworld.deep.ext2.Raptor setWingspan(double value) { + internalSetWingspan(value); + return this; + } + + @Override + public test.openworld.deep.ext2.Raptor setName(String value) { + internalSetName(value); + return this; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SPEED__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.base.impl.Bird_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SPEED__PROP: return getSpeed(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SPEED__PROP: internalSetSpeed((double) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SPEED__PROP); + out.value(getSpeed()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SPEED__PROP: setSpeed(in.nextDouble()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext2.Raptor} type. */ + public static final String RAPTOR__XML_ELEMENT = "raptor"; + + /** XML attribute or element name of a {@link #getSpeed} property. */ + private static final String SPEED__XML_ATTR = "speed"; + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(SPEED__XML_ATTR, Double.toString(getSpeed())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext2.Raptor} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Raptor_Impl readRaptor_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case Eagle_Impl.EAGLE__XML_ELEMENT: { + return test.openworld.deep.ext2.impl.Eagle_Impl.readEagle_XmlContent(in); + } + + default: { + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case SPEED__XML_ATTR: { + setSpeed(Double.parseDouble(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SPEED__XML_ATTR: { + setSpeed(Double.parseDouble(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public final R visit(test.openworld.deep.base.Bird.Visitor v, A arg) throws E { + if (v instanceof test.openworld.deep.ext2.Raptor.Visitor) { + return visit((test.openworld.deep.ext2.Raptor.Visitor) v, arg); + } + return v.visitDefault(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Shark_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Shark_Impl.java new file mode 100644 index 00000000..e9b51408 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/deep/ext2/impl/Shark_Impl.java @@ -0,0 +1,187 @@ +package test.openworld.deep.ext2.impl; + +/** + * Implementation of {@link test.openworld.deep.ext2.Shark}. + */ +public class Shark_Impl extends test.openworld.deep.ext1.impl.Fish_Impl implements test.openworld.deep.ext2.Shark { + + private int _teeth = 0; + + /** + * Creates a {@link Shark_Impl} instance. + * + * @see test.openworld.deep.ext2.Shark#create() + */ + public Shark_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final int getTeeth() { + return _teeth; + } + + @Override + public test.openworld.deep.ext2.Shark setTeeth(int value) { + internalSetTeeth(value); + return this; + } + + /** Internal setter for {@link #getTeeth()} without chain call utility. */ + protected final void internalSetTeeth(int value) { + _listener.beforeSet(this, TEETH__PROP, value); + _teeth = value; + _listener.afterChanged(this, TEETH__PROP); + } + + @Override + public test.openworld.deep.ext2.Shark setFins(int value) { + internalSetFins(value); + return this; + } + + @Override + public test.openworld.deep.ext2.Shark setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return SHARK__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + TEETH__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.deep.ext1.impl.Fish_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.deep.ext1.impl.Fish_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case TEETH__PROP: return getTeeth(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case TEETH__PROP: internalSetTeeth((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(TEETH__PROP); + out.value(getTeeth()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case TEETH__PROP: setTeeth(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.deep.ext2.Shark} type. */ + public static final String SHARK__XML_ELEMENT = "shark"; + + /** XML attribute or element name of a {@link #getTeeth} property. */ + private static final String TEETH__XML_ATTR = "teeth"; + + @Override + public String getXmlTagName() { + return SHARK__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(TEETH__XML_ATTR, Integer.toString(getTeeth())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.deep.ext2.Shark} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shark_Impl readShark_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Shark_Impl result = new Shark_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case TEETH__XML_ATTR: { + setTeeth(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case TEETH__XML_ATTR: { + setTeeth(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + + @Override + public R visit(test.openworld.deep.ext1.Fish.Visitor v, A arg) throws E { + if (v instanceof test.openworld.deep.ext2.Shark.Visitor) { + return ((test.openworld.deep.ext2.Shark.Visitor) v).visit(this, arg); + } + return v.visitDefault(this, arg); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext1/Ext1Types.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext1/Ext1Types.java index ef69c776..1fe4cac1 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext1/Ext1Types.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext1/Ext1Types.java @@ -8,6 +8,7 @@ public class Ext1Types implements de.haumacher.msgbuf.data.TypeRegistration { @Override public void register() { test.openworld.base.SSEEvent.register(test.openworld.ext1.GraphPatchEvent.GRAPH_PATCH_EVENT__TYPE, test.openworld.ext1.GraphPatchEvent::create); + test.openworld.base.SSEEvent.registerXml(test.openworld.ext1.impl.GraphPatchEvent_Impl.GRAPH_PATCH_EVENT__XML_ELEMENT, test.openworld.ext1.GraphPatchEvent::create); } /** diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext2/Ext2Types.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext2/Ext2Types.java index 981d3565..91522e8d 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext2/Ext2Types.java +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/ext2/Ext2Types.java @@ -8,6 +8,7 @@ public class Ext2Types implements de.haumacher.msgbuf.data.TypeRegistration { @Override public void register() { test.openworld.base.SSEEvent.register(test.openworld.ext2.AnalyticsPatchEvent.ANALYTICS_PATCH_EVENT__TYPE, test.openworld.ext2.AnalyticsPatchEvent::create); + test.openworld.base.SSEEvent.registerXml(test.openworld.ext2.impl.AnalyticsPatchEvent_Impl.ANALYTICS_PATCH_EVENT__XML_ELEMENT, test.openworld.ext2.AnalyticsPatchEvent::create); } /** diff --git a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration index a3eef857..e3a8b0c9 100644 --- a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration +++ b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration @@ -1,4 +1,6 @@ +test.openworld.deep.ext2.Ext2Types test.openworld.ext1.Ext1Types test.nested.owcount.OwcountTypes test.openworld.ext2.Ext2Types test.nested.owext.OwextTypes +test.openworld.deep.ext1.Ext1Types From c27f297b9cda4f6223983a8f35b359111e51f93b Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 17:46:39 +0200 Subject: [PATCH 14/20] Reject extensions across files whose options generate incompatible code. A specialization implements the abstract methods and overrides the generated methods of its generalization. When the files of the two disagreed on an option that shapes these methods, the generator produced code that did not compile (#37, #39, #40). A measured matrix over all file options, for a closed hierarchy split into files and for an OpenWorld hierarchy, gave the rule the validation now enforces. Both files must agree on the formats, NoVisitor, NoVisitorExceptions (with visitors), NoTypeKind and NoInterfaces. A specialization may drop listener or reflection support, but not add it. The only compiling case that is now rejected is NoJson on an OpenWorld extension alone: it wrote the extension without its own fields and could not read it back. Also following the #25 decision to reject inconsistent OpenWorld annotations, OpenWorld on a file whose hierarchy root is in a file without it (#38) and OpenWorld combined with SharedGraph or NoInterfaces (#41, before only printed) are rejected. NoVisitor now also suppresses the visitor of extension types (#39). Closes #37 Closes #38 Closes #39 Closes #40 Closes #41 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + README.md | 9 +- .../haumacher/msgbuf/generator/Generator.java | 109 ++++++++- .../msgbuf/generator/MessageGenerator.java | 20 +- .../openworld/TestOpenWorldNoVisitor.java | 36 +++ .../test/openworld/novisitor/base/Circle.java | 41 ++++ .../test/openworld/novisitor/base/Shape.java | 85 +++++++ .../test/openworld/novisitor/base/base.proto | 13 + .../novisitor/base/impl/Circle_Impl.java | 173 ++++++++++++++ .../novisitor/base/impl/Shape_Impl.java | 223 ++++++++++++++++++ .../openworld/novisitor/ext/ExtTypes.java | 20 ++ .../test/openworld/novisitor/ext/Square.java | 41 ++++ .../test/openworld/novisitor/ext/ext.proto | 8 + .../novisitor/ext/impl/Square_Impl.java | 173 ++++++++++++++ .../test/validation/TestExtensionOptions.java | 75 ++++++ .../de.haumacher.msgbuf.data.TypeRegistration | 1 + .../reject/options/base/events.proto | 7 + .../resources/reject/options/base/quiet.proto | 9 + .../reject/options/ext/mismatch.proto | 15 ++ .../test/resources/reject/options/graph.proto | 9 + .../resources/reject/options/split/mid.proto | 8 + .../resources/reject/options/split/root.proto | 5 + 22 files changed, 1073 insertions(+), 15 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorldNoVisitor.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Circle.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Shape.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Circle_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Shape_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ExtTypes.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/Square.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ext.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/impl/Square_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/validation/TestExtensionOptions.java create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/events.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/quiet.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/ext/mismatch.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/graph.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/mid.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/root.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 48ca58ad..d2863086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,14 @@ are rejected with an error instead of crashing the generator. - **Nested specializations of the outer message** (#32): A message nested in its own generalization (e.g. `abstract message Expr { message Sum extends Expr {…} }`) crashed the generator with a `StackOverflowError`. +- **Consistent options across `extends`** (#37, #38, #39, #40, #41): A message that extends a message of another + file is rejected if the files disagree on the serialization formats, `NoVisitor`, `NoVisitorExceptions`, + `NoTypeKind` or `NoInterfaces`, or if it adds listener or reflection support its generalization lacks. These + combinations generated uncompilable code. The exception is `NoJson` (or `NoXml`) only on an OpenWorld extension + file: it compiled, but the extension type was written without its own fields and could not be read. It is rejected + now as well. `option OpenWorld` on a file whose hierarchy root is in a file without it, and `OpenWorld` combined + with `SharedGraph` or `NoInterfaces` (before only a message on the console), are rejected. `option NoVisitor` now + also suppresses the visitor of OpenWorld extension types. - **OpenWorld readers of abstract intermediates** (#26): The JSON reader of an abstract message below the root of an `option OpenWorld` hierarchy (e.g. `Bird` in `Animal > Bird > Parrot`, top-level or nested) no longer fails to compile. It reads the types of other files registered with the root, if they are specializations of the message; a diff --git a/README.md b/README.md index 3995477f..3c102b51 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,12 @@ another file only if both files use `option SharedGraph`, or neither does. Enums `option SharedGraph`. `transient` fields and derived references (`@Container`, `@Reverse`) are not serialized, so they don't need these formats. +A message that extends a message of another file implements and overrides its generated methods. So both files must +agree on the serialization formats, `option NoVisitor`, `option NoVisitorExceptions`, `option NoTypeKind` and +`option NoInterfaces`. A specialization may be generated without the listener (`option NoListener`) or reflection +(`option NoReflection`) support of its generalization, but not with support its generalization lacks. The generator +rejects other combinations with an error naming both files. + ### `option NoXmlNames` Disables generation of constants for the XML format. @@ -327,7 +333,8 @@ itself be extended in further files, if the extension file declares `option Open Implications: - Implies `option NoBinary` (only JSON and XML serialization are supported) -- Cannot be combined with `option NoInterfaces` +- Cannot be combined with `option NoInterfaces` or `option SharedGraph` +- The root's file must declare `option OpenWorld` if any file of the hierarchy does - The generated `Visitor` interface includes a `visitDefault()` fallback method for unknown extension types - Extension types generate their own `Visitor` sub-interface with an `instanceof`-based dispatch diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 0872c8a9..21834e87 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -175,8 +175,9 @@ public void generate(GeneratorPlugin plugin) { buildSpecializations(file); } + List errors = new ArrayList<>(); for (DefinitionFile file : _files) { - validateOpenWorld(file); + validateOpenWorld(file, errors); } // Propagate NoBinary and NoTypeKind to extension files that extend OpenWorld bases @@ -184,10 +185,9 @@ public void generate(GeneratorPlugin plugin) { propagateOpenWorldOptions(file); } - List errors = new ArrayList<>(); for (DefinitionFile file : _files) { if (!_importedFiles.contains(file)) { - validateGeneralizations(file, errors); + validateGeneralizations(file, plugin, errors); } } if (!errors.isEmpty()) { @@ -315,7 +315,7 @@ private static String moduleSpecifier(File from, File to) { return relative.startsWith("../") ? relative : "./" + relative; } - private void validateOpenWorld(DefinitionFile file) { + private void validateOpenWorld(DefinitionFile file, List errors) { boolean openWorld = Util.getFlag(file, "OpenWorld"); if (!openWorld) { return; @@ -323,9 +323,14 @@ private void validateOpenWorld(DefinitionFile file) { // OpenWorld implies NoBinary file.getOptions().put("NoBinary", Flag.create().setValue(true)); - boolean noInterfaces = Util.getFlag(file, "NoInterfaces"); - if (noInterfaces) { - error("option OpenWorld cannot be combined with option NoInterfaces."); + if (_importedFiles.contains(file)) { + return; + } + for (String option : new String[] { "NoInterfaces", "SharedGraph" }) { + if (Util.getFlag(file, option)) { + errors.add(sourceDescription(file) + ": option OpenWorld cannot be combined with option " + option + + ". Remove one of the options."); + } } } @@ -371,19 +376,20 @@ private static boolean extendsOpenWorldFromOtherFile(DefinitionFile file, List */ - private void validateGeneralizations(DefinitionFile file, List errors) { + private void validateGeneralizations(DefinitionFile file, GeneratorPlugin plugin, List errors) { for (Definition def : file.getDefinitions()) { - validateGeneralizations(file, def, errors); + validateGeneralizations(file, def, plugin, errors); } } - private void validateGeneralizations(DefinitionFile file, Definition def, List errors) { + private void validateGeneralizations(DefinitionFile file, Definition def, GeneratorPlugin plugin, List errors) { if (!(def instanceof MessageDef)) { return; } MessageDef message = (MessageDef) def; MessageDef extended = message.getExtendedDef(); if (extended != null) { + int errorCount = errors.size(); List path = new ArrayList<>(); path.add(message); for (MessageDef current = extended; current != null; current = current.getExtendedDef()) { @@ -412,10 +418,91 @@ private void validateGeneralizations(DefinitionFile file, Definition def, List seen = new HashSet<>(); + while (root.getExtendedDef() != null && seen.add(root)) { + root = root.getExtendedDef(); + } + DefinitionFile rootFile = Util.definingFile(root); + if (!Util.getFlag(rootFile, "OpenWorld")) { + errors.add(sourceDescription(file) + ": File declares option OpenWorld, but message '" + + Util.toString(message) + "' belongs to the hierarchy of '" + Util.toString(root) + "' of '" + + sourceDescription(rootFile) + "', which does not declare option OpenWorld. Add 'option OpenWorld;' to '" + + sourceDescription(rootFile) + "', or remove it from '" + sourceDescription(file) + "'."); + } + } + + if (extendedFile != file && errors.size() == errorCount) { + validateExtensionOptions(file, message, extended, extendedFile, plugin, errors); + } } for (Definition inner : message.getDefinitions()) { - validateGeneralizations(file, inner, errors); + validateGeneralizations(file, inner, plugin, errors); + } + } + + /** + * Rejects an extension of a message of another file, if the two files generate incompatible + * code. + * + *

+ * A specialization implements the abstract methods and overrides the methods of its + * generalization. So both files must generate the same serialization formats, visitors and type + * kinds, and use the same interface mode. A specialization may omit listener and reflection + * support of its generalization, but cannot add it. + *

+ */ + private void validateExtensionOptions(DefinitionFile file, MessageDef message, MessageDef extended, + DefinitionFile extendedFile, GeneratorPlugin plugin, List errors) { + String prefix = sourceDescription(file) + ": Message '" + Util.toString(message) + "' extends message '" + + Util.toString(extended) + "' of '" + sourceDescription(extendedFile) + "'"; + + Set formats = formats(file, plugin); + Set extendedFormats = formats(extendedFile, plugin); + for (String format : extendedFormats) { + if (!formats.contains(format) && !format.equals(GRAPH_JSON_FORMAT)) { + errors.add(prefix + ", which is generated with " + format + " serialization, but '" + + sourceDescription(file) + "' is generated without (" + disabledBy(file, format) + + "). Use the same format options in both files."); + } + } + + Map options = file.getOptions(); + Map extendedOptions = extendedFile.getOptions(); + boolean visitor = !MessageGenerator.isTrue(options.get("NoVisitor"), false); + boolean extendedVisitor = !MessageGenerator.isTrue(extendedOptions.get("NoVisitor"), false); + checkSameOption(prefix, file, extendedFile, "NoVisitor", errors); + if (visitor && extendedVisitor) { + checkSameOption(prefix, file, extendedFile, "NoVisitorExceptions", errors); + } + checkSameOption(prefix, file, extendedFile, "NoTypeKind", errors); + checkSameOption(prefix, file, extendedFile, "NoInterfaces", errors); + + boolean listener = MessageGenerator.isListener(options); + boolean reflection = MessageGenerator.isReflection(options); + if (listener && !MessageGenerator.isListener(extendedOptions)) { + errors.add(prefix + ", which is generated without listener support (option NoListener), but '" + + sourceDescription(file) + "' is generated with it. Add 'option NoListener;' to '" + + sourceDescription(file) + "', or remove it from '" + sourceDescription(extendedFile) + "'."); + } else if (reflection && !MessageGenerator.isReflection(extendedOptions)) { + errors.add(prefix + ", which is generated without reflection (option NoReflection), but '" + + sourceDescription(file) + "' is generated with it. Add 'option NoReflection;' and 'option NoListener;' to '" + + sourceDescription(file) + "', or remove them from '" + sourceDescription(extendedFile) + "'."); + } + } + + private void checkSameOption(String prefix, DefinitionFile file, DefinitionFile extendedFile, String option, + List errors) { + boolean set = MessageGenerator.isTrue(file.getOptions().get(option), false); + boolean extendedSet = MessageGenerator.isTrue(extendedFile.getOptions().get(option), false); + if (set != extendedSet) { + DefinitionFile with = set ? file : extendedFile; + DefinitionFile without = set ? extendedFile : file; + errors.add(prefix + ", but only '" + sourceDescription(with) + "' declares option " + option + + ", '" + sourceDescription(without) + "' does not. Use the same setting in both files."); } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index cf9a3431..4465f381 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -68,8 +68,8 @@ public MessageGenerator(NameTable table, Map options, boolean is _graph = isTrue(options.get("SharedGraph"), false); _json = isJson(options); _binary = isBinary(options); - _listener = _graph || !isTrue(options.get("NoListener"), false); - _reflection = _listener || !isTrue(options.get("NoReflection"), false); + _listener = isListener(options); + _reflection = isReflection(options); _visitor = !isTrue(options.get("NoVisitor"), false); _visitEx= !isTrue(options.get("NoVisitorExceptions"), false); _typeKind = !isTrue(options.get("NoTypeKind"), false); @@ -269,7 +269,7 @@ private void generateClassContents() { if (_visitor) { generateVisitorInterface(); } - if (isCrossFileExtension() && !_def.isAbstract() && (_interface || _noInterfaces)) { + if (_visitor && isCrossFileExtension() && !_def.isAbstract() && (_interface || _noInterfaces)) { generateExtensionVisitorInterface(); } } @@ -434,6 +434,20 @@ private void generateInnerDefinitions() { } } + /** + * Whether listener support is generated for the given file options. + */ + public static boolean isListener(Map options) { + return isTrue(options.get("SharedGraph"), false) || !isTrue(options.get("NoListener"), false); + } + + /** + * Whether reflective property access is generated for the given file options. + */ + public static boolean isReflection(Map options) { + return isListener(options) || !isTrue(options.get("NoReflection"), false); + } + /** * Whether JSON serialization code is generated for the given file options. */ diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorldNoVisitor.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorldNoVisitor.java new file mode 100644 index 00000000..6b45f13d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/TestOpenWorldNoVisitor.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.openworld; + +import java.io.IOException; + +import de.haumacher.msgbuf.io.StringR; +import de.haumacher.msgbuf.json.JsonReader; +import junit.framework.TestCase; +import test.openworld.novisitor.base.Shape; +import test.openworld.novisitor.ext.Square; + +/** + * Test case for an OpenWorld hierarchy without visitors (issue #39). + */ +@SuppressWarnings("javadoc") +public class TestOpenWorldNoVisitor extends TestCase { + + public void testExtensionRoundTrip() throws IOException { + Square square = Square.create().setSide(3); + square.setName("s"); + String json = square.toString(); + assertEquals("[\"Square\",{\"name\":\"s\",\"side\":3}]", json); + Shape copy = Shape.readShape(new JsonReader(new StringR(json))); + assertTrue(copy instanceof Square); + assertEquals(json, copy.toString()); + } + + public void testNoVisitor() { + for (Class type : Square.class.getClasses()) { + assertFalse("Unexpected " + type.getName(), type.getSimpleName().equals("Visitor")); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Circle.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Circle.java new file mode 100644 index 00000000..6bd287a6 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Circle.java @@ -0,0 +1,41 @@ +package test.openworld.novisitor.base; + +public interface Circle extends test.openworld.novisitor.base.Shape { + + /** + * Creates a {@link test.openworld.novisitor.base.Circle} instance. + */ + static test.openworld.novisitor.base.Circle create() { + return new test.openworld.novisitor.base.impl.Circle_Impl(); + } + + /** Identifier for the {@link test.openworld.novisitor.base.Circle} type in JSON format. */ + String CIRCLE__TYPE = "Circle"; + + /** @see #getRadius() */ + String RADIUS__PROP = "radius"; + + int getRadius(); + + /** + * @see #getRadius() + */ + test.openworld.novisitor.base.Circle setRadius(int value); + + @Override + test.openworld.novisitor.base.Circle setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.novisitor.base.Circle readCircle(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.novisitor.base.impl.Circle_Impl result = new test.openworld.novisitor.base.impl.Circle_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Circle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Circle readCircle(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.novisitor.base.impl.Circle_Impl.readCircle_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Shape.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Shape.java new file mode 100644 index 00000000..07575e81 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/Shape.java @@ -0,0 +1,85 @@ +package test.openworld.novisitor.base; + +/** + * An OpenWorld hierarchy without visitors (issue #39). + */ +public interface Shape extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** Type codes for the {@link test.openworld.novisitor.base.Shape} hierarchy. */ + public enum TypeKind { + + /** Type literal for {@link test.openworld.novisitor.base.Circle}. */ + CIRCLE, + ; + + } + + /** Registry for dynamically registered subtypes. */ + static final java.util.Map> REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for polymorphic deserialization. + */ + static void register(String typeId, de.haumacher.msgbuf.data.Factory factory) { + REGISTRY.put(typeId, factory); + } + + /** @see #getName() */ + String NAME__PROP = "name"; + + /** The type code of this instance. */ + TypeKind kind(); + + String getName(); + + /** + * @see #getName() + */ + test.openworld.novisitor.base.Shape setName(String value); + + @Override + public test.openworld.novisitor.base.Shape registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.openworld.novisitor.base.Shape unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.openworld.novisitor.base.Shape readShape(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.novisitor.base.Shape result; + in.beginArray(); + String type = in.nextString(); + switch (type) { + case Circle.CIRCLE__TYPE: result = test.openworld.novisitor.base.Circle.readCircle(in); break; + default: { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + de.haumacher.msgbuf.data.Factory factory = test.openworld.novisitor.base.Shape.REGISTRY.get(type); + if (factory != null) { + result = factory.create(); + result.readContent(in); + } else { + in.skipValue(); + result = null; + } + } break; + } + in.endArray(); + return result; + } + + /** Registry for dynamically registered subtypes by their XML element names. */ + static final java.util.Map> XML_REGISTRY = new java.util.HashMap<>(); + + /** + * Registers a subtype factory for reading elements with the given name in XML format. + */ + static void registerXml(String elementName, de.haumacher.msgbuf.data.Factory factory) { + XML_REGISTRY.put(elementName, factory); + } + + /** Creates a new {@link Shape} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shape readShape(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.novisitor.base.impl.Shape_Impl.readShape_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/base.proto b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/base.proto new file mode 100644 index 00000000..42ec546c --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/base.proto @@ -0,0 +1,13 @@ +package test.openworld.novisitor.base; + +option OpenWorld; +option NoVisitor; + +/** An OpenWorld hierarchy without visitors (issue #39). */ +abstract message Shape { + string name; +} + +message Circle extends Shape { + int radius; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Circle_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Circle_Impl.java new file mode 100644 index 00000000..d3ecaa7f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Circle_Impl.java @@ -0,0 +1,173 @@ +package test.openworld.novisitor.base.impl; + +/** + * Implementation of {@link test.openworld.novisitor.base.Circle}. + */ +public class Circle_Impl extends test.openworld.novisitor.base.impl.Shape_Impl implements test.openworld.novisitor.base.Circle { + + private int _radius = 0; + + /** + * Creates a {@link Circle_Impl} instance. + * + * @see test.openworld.novisitor.base.Circle#create() + */ + public Circle_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return TypeKind.CIRCLE; + } + + @Override + public final int getRadius() { + return _radius; + } + + @Override + public test.openworld.novisitor.base.Circle setRadius(int value) { + internalSetRadius(value); + return this; + } + + /** Internal setter for {@link #getRadius()} without chain call utility. */ + protected final void internalSetRadius(int value) { + _listener.beforeSet(this, RADIUS__PROP, value); + _radius = value; + _listener.afterChanged(this, RADIUS__PROP); + } + + @Override + public test.openworld.novisitor.base.Circle setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return CIRCLE__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + RADIUS__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.novisitor.base.impl.Shape_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.novisitor.base.impl.Shape_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case RADIUS__PROP: return getRadius(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case RADIUS__PROP: internalSetRadius((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(RADIUS__PROP); + out.value(getRadius()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case RADIUS__PROP: setRadius(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.novisitor.base.Circle} type. */ + public static final String CIRCLE__XML_ELEMENT = "circle"; + + /** XML attribute or element name of a {@link #getRadius} property. */ + private static final String RADIUS__XML_ATTR = "radius"; + + @Override + public String getXmlTagName() { + return CIRCLE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(RADIUS__XML_ATTR, Integer.toString(getRadius())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.novisitor.base.Circle} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Circle_Impl readCircle_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Circle_Impl result = new Circle_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case RADIUS__XML_ATTR: { + setRadius(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case RADIUS__XML_ATTR: { + setRadius(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Shape_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Shape_Impl.java new file mode 100644 index 00000000..daa603af --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/base/impl/Shape_Impl.java @@ -0,0 +1,223 @@ +package test.openworld.novisitor.base.impl; + +/** + * Implementation of {@link test.openworld.novisitor.base.Shape}. + */ +public abstract class Shape_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.openworld.novisitor.base.Shape { + + static { + de.haumacher.msgbuf.data.TypeRegistryLoader.ensureLoaded(); + } + + private String _name = ""; + + /** + * Creates a {@link Shape_Impl} instance. + */ + public Shape_Impl() { + super(); + } + + @Override + public final String getName() { + return _name; + } + + @Override + public test.openworld.novisitor.base.Shape setName(String value) { + internalSetName(value); + return this; + } + + /** Internal setter for {@link #getName()} without chain call utility. */ + protected final void internalSetName(String value) { + _listener.beforeSet(this, NAME__PROP, value); + _name = value; + _listener.afterChanged(this, NAME__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.openworld.novisitor.base.Shape registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.openworld.novisitor.base.Shape unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + NAME__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case NAME__PROP: return getName(); + default: return test.openworld.novisitor.base.Shape.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case NAME__PROP: internalSetName((String) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.beginArray(); + out.value(jsonType()); + writeContent(out); + out.endArray(); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(NAME__PROP); + out.value(getName()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case NAME__PROP: setName(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.novisitor.base.Shape} type. */ + public static final String SHAPE__XML_ELEMENT = "shape"; + + /** XML attribute or element name of a {@link #getName} property. */ + private static final String NAME__XML_ATTR = "name"; + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(NAME__XML_ATTR, getName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.openworld.novisitor.base.Shape} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Shape_Impl readShape_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + switch (in.getLocalName()) { + case Circle_Impl.CIRCLE__XML_ELEMENT: { + return test.openworld.novisitor.base.impl.Circle_Impl.readCircle_XmlContent(in); + } + + default: { + de.haumacher.msgbuf.data.Factory factory = test.openworld.novisitor.base.Shape.XML_REGISTRY.get(in.getLocalName()); + test.openworld.novisitor.base.Shape instance = factory == null ? null : factory.create(); + if (instance instanceof Shape_Impl) { + Shape_Impl result = (Shape_Impl) instance; + result.readContentXml(in); + return result; + } + internalSkipUntilMatchingEndElement(in); + return null; + } + } + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case NAME__XML_ATTR: { + setName(value); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case NAME__XML_ATTR: { + setName(in.getElementText()); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ExtTypes.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ExtTypes.java new file mode 100644 index 00000000..8a146ed3 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ExtTypes.java @@ -0,0 +1,20 @@ +package test.openworld.novisitor.ext; + +/** + * Registration of extension types for the OpenWorld protocol. + */ +public class ExtTypes implements de.haumacher.msgbuf.data.TypeRegistration { + + @Override + public void register() { + test.openworld.novisitor.base.Shape.register(test.openworld.novisitor.ext.Square.SQUARE__TYPE, test.openworld.novisitor.ext.Square::create); + test.openworld.novisitor.base.Shape.registerXml(test.openworld.novisitor.ext.impl.Square_Impl.SQUARE__XML_ELEMENT, test.openworld.novisitor.ext.Square::create); + } + + /** + * Explicit initialization for GWT or manual use. + */ + public static void init() { + new ExtTypes().register(); + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/Square.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/Square.java new file mode 100644 index 00000000..ba97b9a3 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/Square.java @@ -0,0 +1,41 @@ +package test.openworld.novisitor.ext; + +public interface Square extends test.openworld.novisitor.base.Shape { + + /** + * Creates a {@link test.openworld.novisitor.ext.Square} instance. + */ + static test.openworld.novisitor.ext.Square create() { + return new test.openworld.novisitor.ext.impl.Square_Impl(); + } + + /** Identifier for the {@link test.openworld.novisitor.ext.Square} type in JSON format. */ + String SQUARE__TYPE = "Square"; + + /** @see #getSide() */ + String SIDE__PROP = "side"; + + int getSide(); + + /** + * @see #getSide() + */ + test.openworld.novisitor.ext.Square setSide(int value); + + @Override + test.openworld.novisitor.ext.Square setName(String value); + + /** Reads a new instance from the given reader. */ + static test.openworld.novisitor.ext.Square readSquare(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.openworld.novisitor.ext.impl.Square_Impl result = new test.openworld.novisitor.ext.impl.Square_Impl(); + result.readContent(in); + return result; + } + + /** Creates a new {@link Square} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Square readSquare(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.openworld.novisitor.ext.impl.Square_Impl.readSquare_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ext.proto b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ext.proto new file mode 100644 index 00000000..6e1bc567 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/ext.proto @@ -0,0 +1,8 @@ +package test.openworld.novisitor.ext; +import "../base/base.proto"; + +option NoVisitor; + +message Square extends test.openworld.novisitor.base.Shape { + int side; +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/impl/Square_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/impl/Square_Impl.java new file mode 100644 index 00000000..b3f18894 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/openworld/novisitor/ext/impl/Square_Impl.java @@ -0,0 +1,173 @@ +package test.openworld.novisitor.ext.impl; + +/** + * Implementation of {@link test.openworld.novisitor.ext.Square}. + */ +public class Square_Impl extends test.openworld.novisitor.base.impl.Shape_Impl implements test.openworld.novisitor.ext.Square { + + private int _side = 0; + + /** + * Creates a {@link Square_Impl} instance. + * + * @see test.openworld.novisitor.ext.Square#create() + */ + public Square_Impl() { + super(); + } + + @Override + public TypeKind kind() { + return null; + } + + @Override + public final int getSide() { + return _side; + } + + @Override + public test.openworld.novisitor.ext.Square setSide(int value) { + internalSetSide(value); + return this; + } + + /** Internal setter for {@link #getSide()} without chain call utility. */ + protected final void internalSetSide(int value) { + _listener.beforeSet(this, SIDE__PROP, value); + _side = value; + _listener.afterChanged(this, SIDE__PROP); + } + + @Override + public test.openworld.novisitor.ext.Square setName(String value) { + internalSetName(value); + return this; + } + + @Override + public String jsonType() { + return SQUARE__TYPE; + } + + @SuppressWarnings("hiding") + protected static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + SIDE__PROP); + java.util.List tmp = new java.util.ArrayList<>(); + tmp.addAll(test.openworld.novisitor.base.impl.Shape_Impl.PROPERTIES); + tmp.addAll(local); + PROPERTIES = java.util.Collections.unmodifiableList(tmp); + } + + @SuppressWarnings("hiding") + protected static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(test.openworld.novisitor.base.impl.Shape_Impl.TRANSIENT_PROPERTIES); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case SIDE__PROP: return getSide(); + default: return super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case SIDE__PROP: internalSetSide((int) value); break; + default: super.set(field, value); break; + } + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(SIDE__PROP); + out.value(getSide()); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case SIDE__PROP: setSide(in.nextInt()); break; + default: super.readField(in, field); + } + } + + /** XML element name representing a {@link test.openworld.novisitor.ext.Square} type. */ + public static final String SQUARE__XML_ELEMENT = "square"; + + /** XML attribute or element name of a {@link #getSide} property. */ + private static final String SIDE__XML_ATTR = "side"; + + @Override + public String getXmlTagName() { + return SQUARE__XML_ELEMENT; + } + + /** Serializes all fields that are written as XML attributes. */ + @Override + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeAttributes(out); + out.writeAttribute(SIDE__XML_ATTR, Integer.toString(getSide())); + } + + /** Serializes all fields that are written as XML elements. */ + @Override + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + super.writeElements(out); + // No element fields. + } + + /** Creates a new {@link test.openworld.novisitor.ext.Square} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Square_Impl readSquare_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Square_Impl result = new Square_Impl(); + result.readContentXml(in); + return result; + } + + @Override + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case SIDE__XML_ATTR: { + setSide(Integer.parseInt(value)); + break; + } + default: { + super.readFieldXmlAttribute(name, value); + } + } + } + + @Override + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case SIDE__XML_ATTR: { + setSide(Integer.parseInt(in.getElementText())); + break; + } + default: { + super.readFieldXmlElement(in, localName); + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestExtensionOptions.java b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestExtensionOptions.java new file mode 100644 index 00000000..5e611a07 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/validation/TestExtensionOptions.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2026 Bernhard Haumacher et al. All Rights Reserved. + */ +package test.validation; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; + +import de.haumacher.msgbuf.generator.Generator; +import de.haumacher.msgbuf.generator.GeneratorException; +import de.haumacher.msgbuf.generator.parser.ParseException; +import de.haumacher.msgbuf.generator.plugins.XmlStreamingPlugin; +import junit.framework.TestCase; + +/** + * Test case for rejecting extensions across files whose options generate incompatible code + * (issues #37, #38, #40, #41). + */ +@SuppressWarnings("javadoc") +public class TestExtensionOptions extends TestCase { + + private static final File FIXTURES = new File("src/test/resources/reject/options"); + + /** Formats, visitors, type kinds must agree; listener support must not be added (#37, #40). */ + public void testMismatchingOptions() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Ping' extends message 'reject.opt.base.Event' of 'reject/opt/base/events.proto', which is generated with JSON serialization, but 'reject/opt/ext/mismatch.proto' is generated without (option NoJson). Use the same format options in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Ping' extends message 'reject.opt.base.Event' of 'reject/opt/base/events.proto', but only 'reject/opt/ext/mismatch.proto' declares option NoVisitor, 'reject/opt/base/events.proto' does not. Use the same setting in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Ping' extends message 'reject.opt.base.Event' of 'reject/opt/base/events.proto', but only 'reject/opt/ext/mismatch.proto' declares option NoTypeKind, 'reject/opt/base/events.proto' does not. Use the same setting in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Loud' extends message 'reject.opt.base.Quiet' of 'reject/opt/base/quiet.proto', which is generated with JSON serialization, but 'reject/opt/ext/mismatch.proto' is generated without (option NoJson). Use the same format options in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Loud' extends message 'reject.opt.base.Quiet' of 'reject/opt/base/quiet.proto', but only 'reject/opt/ext/mismatch.proto' declares option NoVisitor, 'reject/opt/base/quiet.proto' does not. Use the same setting in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Loud' extends message 'reject.opt.base.Quiet' of 'reject/opt/base/quiet.proto', but only 'reject/opt/ext/mismatch.proto' declares option NoTypeKind, 'reject/opt/base/quiet.proto' does not. Use the same setting in both files.", + "reject/opt/ext/mismatch.proto: Message 'reject.opt.ext.Loud' extends message 'reject.opt.base.Quiet' of 'reject/opt/base/quiet.proto', which is generated without listener support (option NoListener), but 'reject/opt/ext/mismatch.proto' is generated with it. Add 'option NoListener;' to 'reject/opt/ext/mismatch.proto', or remove it from 'reject/opt/base/quiet.proto'."), + reject("ext/mismatch.proto")); + } + + /** OpenWorld on an intermediate requires OpenWorld on the root (#38). */ + public void testOpenWorldIntermediateOfClosedRoot() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/opt/split/mid.proto: File declares option OpenWorld, but message 'reject.opt.split.Mid' belongs to the hierarchy of 'reject.opt.split.Root' of 'reject/opt/split/root.proto', which does not declare option OpenWorld. Add 'option OpenWorld;' to 'reject/opt/split/root.proto', or remove it from 'reject/opt/split/mid.proto'."), + reject("split/root.proto", "split/mid.proto")); + } + + /** OpenWorld cannot be combined with NoInterfaces or SharedGraph (#41). */ + public void testOpenWorldCombinations() throws IOException, ParseException { + assertEquals(Arrays.asList( + "reject/opt/graph/graph.proto: option OpenWorld cannot be combined with option NoInterfaces. Remove one of the options.", + "reject/opt/graph/graph.proto: option OpenWorld cannot be combined with option SharedGraph. Remove one of the options."), + reject("graph.proto")); + } + + private List reject(String... protos) throws IOException, ParseException { + File target = new File("target"); + target.mkdirs(); + File out = Files.createTempDirectory(target.toPath(), getName()).toFile(); + Generator generator = new Generator(); + generator.setOut(out); + for (String proto : protos) { + generator.load(new File(FIXTURES, proto)); + } + try { + generator.generate(new XmlStreamingPlugin()); + fail("Expected rejection of " + Arrays.toString(protos) + "."); + return null; + } catch (GeneratorException ex) { + String[] written = out.list(); + assertTrue("No code must be generated for rejected definitions.", written == null || written.length == 0); + return ex.getErrors(); + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration index e3a8b0c9..20e9ff21 100644 --- a/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration +++ b/de.haumacher.msgbuf.generator/src/test/resources/META-INF/services/de.haumacher.msgbuf.data.TypeRegistration @@ -1,4 +1,5 @@ test.openworld.deep.ext2.Ext2Types +test.openworld.novisitor.ext.ExtTypes test.openworld.ext1.Ext1Types test.nested.owcount.OwcountTypes test.openworld.ext2.Ext2Types diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/events.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/events.proto new file mode 100644 index 00000000..ef334100 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/events.proto @@ -0,0 +1,7 @@ +package reject.opt.base; + +option OpenWorld; + +abstract message Event { + string source; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/quiet.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/quiet.proto new file mode 100644 index 00000000..b7881c29 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/base/quiet.proto @@ -0,0 +1,9 @@ +package reject.opt.base; + +option OpenWorld; +option NoReflection; +option NoListener; + +abstract message Quiet { + string source; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/ext/mismatch.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/ext/mismatch.proto new file mode 100644 index 00000000..b17f8b5b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/ext/mismatch.proto @@ -0,0 +1,15 @@ +package reject.opt.ext; +import "../base/events.proto"; +import "../base/quiet.proto"; + +option NoJson; +option NoVisitor; +option NoTypeKind; + +message Ping extends reject.opt.base.Event { + int count; +} + +message Loud extends reject.opt.base.Quiet { + int volume; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/graph.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/graph.proto new file mode 100644 index 00000000..ace11ea7 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/graph.proto @@ -0,0 +1,9 @@ +package reject.opt.graph; + +option OpenWorld; +option SharedGraph; +option NoInterfaces; + +abstract message Node { + string name; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/mid.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/mid.proto new file mode 100644 index 00000000..737f68fe --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/mid.proto @@ -0,0 +1,8 @@ +package reject.opt.split; +import "root.proto"; + +option OpenWorld; + +abstract message Mid extends Root { + int level; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/root.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/root.proto new file mode 100644 index 00000000..507b5e83 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/options/split/root.proto @@ -0,0 +1,5 @@ +package reject.opt.split; + +abstract message Root { + string name; +} From 32e827ecee97d20f13eb454e9c5db58067133bc2 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 18:22:20 +0200 Subject: [PATCH 15/20] Generate visitor, tag and guard helpers for polymorphic values in TypeScript. The TypeScript target described the JSON format with types only, so a client still had to dispatch type-tagged values by hand, e.g. the events of an SSE stream, with a switch that silently misses new event types. JSON values are plain JavaScript data, so no generated classes or TypeScript runtime are needed: for each Any...Json union, the module now contains a visitor interface with an exhaustive dispatch function (a new type in the protocol is a compile error in every handler; OpenWorld hierarchies get a required visitDefault) and a type guard checking the type tag, plus a function creating the type-tagged tuple per concrete type. The helpers live at module top level even for nested messages, since namespaces with values are not erasable syntax. Names are derived from the outer-qualified message name, and names that would still clash are rejected before any output is written. Files with option SharedGraph get no helpers, since their JSON format is not described by the types either. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- README.md | 51 +- .../haumacher/msgbuf/generator/Generator.java | 18 +- .../generator/ts/TypeScriptGenerator.java | 378 +++++++++++- .../generator/ts/TestTypeScriptGenerator.java | 43 ++ .../resources/reject/ts/collide/names.proto | 15 + .../test/resources/reject/ts/open/base.proto | 6 + .../test/resources/reject/ts/open/one.proto | 6 + .../test/resources/reject/ts/open/two.proto | 7 + .../ts/expected/test/ts/commands/commands.ts | 549 ++++++++++++++++++ .../ts/expected/test/ts/common/common.ts | 59 +- .../ts/expected/test/ts/events/base/base.ts | 197 +++++++ .../ts/expected/test/ts/events/ext/ext.ts | 116 ++++ .../ts/expected/test/ts/graph/graph.ts | 28 + .../ts/expected/test/ts/shapes/shapes.ts | 108 +++- .../ts/proto/test/ts/commands/commands.proto | 127 ++++ .../ts/proto/test/ts/events/base/base.proto | 40 ++ .../ts/proto/test/ts/events/ext/ext.proto | 35 ++ .../ts/proto/test/ts/graph/graph.proto | 15 + 19 files changed, 1793 insertions(+), 12 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/ts/collide/names.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/one.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/two.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/commands/commands.ts create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/base/base.ts create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/ext/ext.ts create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/graph/graph.ts create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/commands/commands.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/base/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/ext/ext.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/graph/graph.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index d2863086..51fa9f49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,12 +3,17 @@ ## 1.2.3 ### New Features -- **TypeScript type definitions**: Generate a types-only TypeScript module per `.proto` file describing its JSON +- **TypeScript type definitions**: Generate a TypeScript module per `.proto` file describing its JSON format (interfaces for messages, string-literal unions for enums, type-tagged tuple unions for polymorphic values). Top-level types are named with the suffix `Json` (e.g. `ShapeJson`, `AnyShapeJson`), since they describe the JSON format, not the data itself. Properties the Java writer always emits are required, only nullable fields are optional. Enabled for all files with the Maven plugin parameter `typeScriptOutputDirectory` or the `-ts
` CLI argument, or per file with `option TypeScript = "path/to/module.ts";`. + For polymorphic values, the modules contain small helpers operating on the plain JSON values (#10): a visitor + interface and an exhaustive dispatch function (`visitShapeJson(value, visitor)`, with a required `visitDefault` for + `option OpenWorld`) and a type guard checking the type tag (`isAnyShapeJson(value)`) per `Any...Json` union, and a + function creating the type-tagged tuple per concrete type (`tagCircle(self)`). No helpers are generated for + `option SharedGraph`. Helper names that would clash (e.g. of `message A_B` and a nested `A.B`) are rejected. - **File documentation comment**: A doc comment before the `syntax` or `package` declaration is kept as the documentation of the `.proto` file (`DefinitionFile.comment`) and emitted as TSDoc `@packageDocumentation` of the TypeScript module. diff --git a/README.md b/README.md index 3c102b51..9c550c2a 100644 --- a/README.md +++ b/README.md @@ -498,8 +498,9 @@ message MyMessage { ### TypeScript type definitions The generator can create a TypeScript module with type definitions for the JSON format of each `.proto` file. The -modules contain types only (no readers, writers or other runtime code) and let a TypeScript client share the protocol -contract with the Java side. +modules let a TypeScript client share the protocol contract with the Java side. Besides the types, they only contain +small helper functions for type-tagged polymorphic values (visitor dispatch, tagging, tag guards, see below) that +operate on the plain values of `JSON.parse()`: no classes, no readers or writers, no runtime library. Since the types describe the JSON format and not the data itself, a top-level type is named after its definition with the suffix `Json`, e.g. `ShapeJson` for `message Shape`. This keeps the plain names free for types representing the @@ -543,6 +544,8 @@ Mapping of protocol definitions: | `map` (other key types) | `Array<{ key: K; value: V }>` | | Nested definitions | Declarations in a namespace named after the outer message, keeping their names, e.g. `OuterJson.Inner` | | Types from imported `.proto` files | `import type { ... } from '';` | +| `abstract message A` with `AnyAJson` | Visitor interface `AJsonVisitor`, dispatch function `visitAJson(value, visitor)`, type guard `isAnyAJson(value)` | +| `message C extends A` (in a hierarchy with abstract root) | Function `tagC(self: CJson): ['TypeIdOfC', CJson]` creating the type-tagged tuple | Details: @@ -572,6 +575,48 @@ Details: generated and used as type of fields referencing `A`. For `option OpenWorld` hierarchies, the union additionally contains `[string, AJson]` for extension types from other modules. References to concrete messages (and all messages in a hierarchy with a concrete root) are written without type information and use the interface directly. +* **Helpers for polymorphic values**: For each union `AnyAJson`, a visitor interface with one method per concrete + type of the union, a dispatch function and a type guard are generated, and a tag function for each concrete type + of such a hierarchy: + + ```ts + export interface SSEEventJsonVisitor { + visitPatchEvent(self: PatchEventJson): R; + visitStateEvent(self: StateEventJson): R; + } + export function visitSSEEventJson(value: AnySSEEventJson, visitor: SSEEventJsonVisitor): R; + export function isAnySSEEventJson(value: unknown): value is AnySSEEventJson; + export function tagPatchEvent(self: PatchEventJson): ['PatchEvent', PatchEventJson]; + ``` + + Usage: + + ```ts + const event: unknown = JSON.parse(data); + if (isAnySSEEventJson(event)) { + visitSSEEventJson(event, { + visitPatchEvent: patch => applyPatch(patch), + visitStateEvent: state => replaceState(state), + }); + } + socket.send(JSON.stringify(tagPatchEvent({ timestamp: Date.now(), patch: '...' }))); + ``` + + * The name part of a helper (`SSEEvent`, `PatchEvent`) is the message name qualified with the names of its outer + messages, joined with `_`, first letter in upper case, e.g. `visitGroup_Info` and `tagGroup_Info` for message + `Info` nested in `Group`. The package is not part of the name. All helpers are declared at the top level of the + module, also for nested messages (a namespace containing functions is not erasable TypeScript syntax). The + generator rejects a `.proto` file whose helper names clash, i.e. two concrete types of one hierarchy (also from + different files) or two messages of one file with the same name part, e.g. `message A_B` and `A.B`. + * A visitor method has the same name in the visitors of all abstract types of a hierarchy, so a visitor of the root + can also be passed to the dispatch function of an abstract intermediate type. + * The dispatch function of a closed hierarchy is checked for exhaustiveness by the compiler and throws an `Error` + for an unknown type ID. For `option OpenWorld` hierarchies, the visitor has an additional required method + `visitDefault(self: AJson, typeId: string)` that receives values of types not known to the module (like the + `visitDefault()` of the Java visitor). + * The type guard checks the type tag only: an array of two elements, the first a known type ID (any string for + `option OpenWorld`), the second an object. The properties of the object are not validated. + * Tag functions return the exact tuple type, which is assignable to each `Any...Json` union containing the type. * **Documentation**: Doc comments become TSDoc comments. JavaDoc inline tags are translated: `{@code x}` becomes `` `x` ``, `{@link Type}`, `{@link #field}` and `{@link Type#field label}` become links to the TypeScript type or property (`{@link Type.prop label}`, using the JSON property name), a link to an enum constant becomes its protocol @@ -583,7 +628,7 @@ Details: at the location the same generator configuration would produce for it (its `option TypeScript`, or its package path within the TypeScript output directory). * **Limitations**: The JSON format of `option SharedGraph` protocols (objects as `[type, id, {...}]`, references as - IDs, incremental updates) is not described by the generated types. A generated `AnyAJson` union type may clash with + IDs, incremental updates) is not described by the generated types, no helper functions are generated for them. A generated `AnyAJson` union type may clash with a message named `AnyA`. ## Installation in Eclipse diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 21834e87..63c9180c 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -216,6 +216,15 @@ public void generate(GeneratorPlugin plugin) { synthesizer.process(file); } + for (DefinitionFile file : _files) { + if (!_importedFiles.contains(file) && generatesTypeScript(file)) { + TypeScriptGenerator.validate(file, this::sourceDescription, errors); + } + } + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } + for (DefinitionFile file : _files) { if (_importedFiles.contains(file)) { continue; // Imported for type resolution only, don't generate code @@ -235,7 +244,7 @@ public void generate(GeneratorPlugin plugin) { new DartLibGenerator(new File(_out, ((StringOption) dartLib).getValue()), file).run(); } - if (_tsOut != null || file.getOptions().get(TYPESCRIPT_OPTION) != null) { + if (generatesTypeScript(file)) { File tsFile = typeScriptModule(file); new TypeScriptGenerator(tsFile, file, sourceDescription(file), other -> moduleSpecifier(tsFile, typeScriptModule(other)), _table).run(); @@ -259,6 +268,13 @@ public void generate(GeneratorPlugin plugin) { } } + /** + * Whether a TypeScript module is generated for the given definitions. + */ + private boolean generatesTypeScript(DefinitionFile file) { + return _tsOut != null || file.getOptions().get(TYPESCRIPT_OPTION) != null; + } + /** * The TypeScript module file for the given definitions. * diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java index 83b71d09..655e2c50 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/ts/TypeScriptGenerator.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Pattern; @@ -34,15 +35,17 @@ import de.haumacher.msgbuf.generator.common.MsgBufJsonProtocol; import de.haumacher.msgbuf.generator.common.Util; import de.haumacher.msgbuf.generator.util.AbstractTypeScriptGenerator; +import de.haumacher.msgbuf.generator.util.CodeUtil; /** * Generator for a TypeScript module with type definitions describing the msgbuf JSON * format of all messages and enums of a .proto file. * *

- * The module contains types only (no runtime code). Since the types describe the JSON format and - * not the data itself, the name of a top-level type is the name of its definition with the suffix - * {@value #JSON_SUFFIX}, e.g. ShapeJson for message Shape: + * The module contains types and, for type-tagged polymorphic values, small helper functions + * operating on plain JSON values (no classes, no readers or writers, no runtime library). Since the + * types describe the JSON format and not the data itself, the name of a top-level type is the name + * of its definition with the suffix {@value #JSON_SUFFIX}, e.g. ShapeJson for message Shape: *

*
    *
  • A message becomes an interface whose properties are named with the JSON @@ -63,6 +66,15 @@ *
  • Nested definitions are placed in a namespace named after the outer message and keep their * names, e.g. GroupJson.Info.
  • *
  • Types from other .proto files are imported with import type.
  • + *
  • For each Any<Name>Json union, a visitor interface + * <Part>JsonVisitor with a method visit<Part> per concrete type + * (and visitDefault for option OpenWorld), a dispatch function + * visit<Part>Json and a type guard isAny<Part>Json checking the + * type tag are generated. Each concrete message in such hierarchy gets a function + * tag<Part> creating its type-tagged tuple. <Part> is the message + * name qualified with the names of its outer messages, joined with _, e.g. + * Group_Info. All helpers are declared at the top level of the module, also + * for nested messages. No helpers are generated for option SharedGraph.
  • *
*/ public class TypeScriptGenerator extends AbstractTypeScriptGenerator { @@ -94,6 +106,11 @@ public class TypeScriptGenerator extends AbstractTypeScriptGenerator { private final NameTable _table; + /** + * Whether helper functions for polymorphic values are generated, see {@link #hasHelpers(DefinitionFile)}. + */ + private final boolean _helpers; + /** * Local names bound per imported file (by top-level name in that file). */ @@ -136,6 +153,7 @@ public TypeScriptGenerator(File file, DefinitionFile proto, String source, Funct _source = source; _moduleSpecifier = moduleSpecifier; _table = table; + _helpers = hasHelpers(proto); } /** @@ -160,11 +178,17 @@ protected void generate() { line("// Generated by msgbuf from '" + _source + "'. Do not edit."); line("//"); - line("// Type definitions for the msgbuf JSON format of the protocol (types only, no runtime code)."); + if (hasHelpers()) { + line("// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its"); + line("// type-tagged polymorphic values (visitor dispatch, tagging, tag guards)."); + } else { + line("// Type definitions for the msgbuf JSON format of the protocol (types only, no runtime code)."); + } if (Util.getFlag(_proto, "SharedGraph")) { line("//"); line("// Note: The protocol uses 'option SharedGraph'. Its JSON format (objects as [type, id, {...}],"); - line("// references as object IDs, incremental updates) is not described by these types."); + line("// references as object IDs, incremental updates) is not described by these types. No helper"); + line("// functions for polymorphic values are generated."); } _separate = true; @@ -188,6 +212,9 @@ protected void generate() { } for (Definition def : _proto.getDefinitions()) { generateDefinition(def); + if (_helpers) { + generateHelpers(def); + } } for (Map.Entry alias : _aliases.entrySet()) { @@ -218,6 +245,11 @@ private void resolveReferences() { _topLevelNames.add(polymorphicName(def)); } } + if (_helpers) { + for (Definition def : _proto.getDefinitions()) { + forEachMessage(def, message -> _topLevelNames.addAll(helperNames(message))); + } + } for (Definition def : _proto.getDefinitions()) { resolveReferences(def); } @@ -259,6 +291,13 @@ private void resolveReferences(Definition def) { } if (hasPolymorphicType(message)) { polymorphicType(message); + if (_helpers) { + // References of the top-level helper declarations. + ref(message, null); + for (MessageDef specialization : Util.concreteTransitiveSpecializations(message)) { + ref(specialization, null); + } + } } for (Definition inner : message.getDefinitions()) { resolveReferences(inner); @@ -341,6 +380,335 @@ private void generateMessage(MessageDef def) { } } + /** + * Whether helper functions for polymorphic values are generated for the given file. + * + *

+ * The JSON format of option SharedGraph is not described by the generated types, + * helpers operating on these types would be misleading. + *

+ */ + private static boolean hasHelpers(DefinitionFile file) { + return !Util.getFlag(file, "SharedGraph"); + } + + /** + * Whether the generated module contains helper functions. + */ + private boolean hasHelpers() { + if (!_helpers) { + return false; + } + boolean[] result = { false }; + for (Definition def : _proto.getDefinitions()) { + forEachMessage(def, message -> result[0] |= !helperNames(message).isEmpty()); + } + return result[0]; + } + + private static void forEachMessage(Definition def, Consumer action) { + if (def instanceof MessageDef) { + MessageDef message = (MessageDef) def; + action.accept(message); + for (Definition inner : message.getDefinitions()) { + forEachMessage(inner, action); + } + } + } + + /** + * Whether a value of the given message is written with a type tag, when referenced through one of + * its abstract generalizations. + * + *

+ * This is the case for a concrete message whose hierarchy root is abstract. + *

+ */ + private static boolean isTagged(MessageDef def) { + return !def.isAbstract() && def.getExtendedDef() != null && root(def).isAbstract(); + } + + /** + * The top-level names of the helper declarations generated for the given message (not + * including the helpers of nested messages). + */ + private static List helperNames(MessageDef def) { + List result = new ArrayList<>(); + if (hasPolymorphicType(def)) { + result.add(visitorName(def)); + result.add(dispatchName(def)); + result.add(guardName(def)); + } + if (isTagged(def)) { + result.add(tagName(def)); + } + return result; + } + + /** + * The name part of helper declarations for the given message. + * + *

+ * The name of the message qualified with the names of its outer messages, separated by + * _, with the first letter in upper case, e.g. Group_Info for + * message Info nested in Group. The package is not part of the name. + *

+ */ + private static String helperPart(MessageDef def) { + List names = new ArrayList<>(); + for (Definition current = def; current != null; current = current.getOuter()) { + names.add(0, current.getName()); + } + return CodeUtil.firstUpperCase(String.join("_", names)); + } + + /** + * Name of the visitor interface for the given abstract message. + */ + private static String visitorName(MessageDef def) { + return helperPart(def) + JSON_SUFFIX + "Visitor"; + } + + /** + * Name of the function dispatching a polymorphic value of the given abstract message to a + * visitor. + */ + private static String dispatchName(MessageDef def) { + return "visit" + helperPart(def) + JSON_SUFFIX; + } + + /** + * Name of the type guard for polymorphic values of the given abstract message. + */ + private static String guardName(MessageDef def) { + return "is" + POLYMORPHIC_PREFIX + helperPart(def) + JSON_SUFFIX; + } + + /** + * Name of the visitor method handling the given concrete message. + */ + private static String visitMethodName(MessageDef def) { + return "visit" + helperPart(def); + } + + /** + * Name of the function creating the type-tagged representation of the given concrete message. + */ + private static String tagName(MessageDef def) { + return "tag" + helperPart(def); + } + + /** + * Whether the polymorphic values of the given abstract message may have types that are not + * known to the generated module (option OpenWorld of the hierarchy root). + */ + private static boolean isOpen(MessageDef def) { + return Util.getFlag(Util.definingFile(root(def)), "OpenWorld"); + } + + /** + * Checks that the names of the TypeScript helper declarations of the given file are unique. + * + *

+ * The visitor method names of a hierarchy must be unique within the hierarchy (also across + * files), and the helper function names of a module must be unique within the module. + *

+ * + * @param file + * The file to generate a TypeScript module for. + * @param source + * Description of a file for error messages. + * @param errors + * The errors found. + */ + public static void validate(DefinitionFile file, Function source, List errors) { + if (!hasHelpers(file)) { + return; + } + Set reported = new HashSet<>(); + Map moduleNames = new LinkedHashMap<>(); + for (Definition def : file.getDefinitions()) { + forEachMessage(def, message -> { + for (String name : helperNames(message)) { + MessageDef clash = moduleNames.putIfAbsent(name, message); + if (clash != null) { + errors.add(source.apply(file) + ": The TypeScript declaration '" + name + "' is generated for message '" + + protoName(clash) + "' and for message '" + protoName(message) + "'. " + renameHint()); + } + } + + if (hasPolymorphicType(message)) { + Map methods = new LinkedHashMap<>(); + for (MessageDef specialization : Util.concreteTransitiveSpecializations(message)) { + String method = visitMethodName(specialization); + MessageDef clash = methods.putIfAbsent(method, specialization); + if (clash != null && reported.add(protoName(clash) + " " + protoName(specialization))) { + errors.add(source.apply(file) + ": The TypeScript visitor '" + visitorName(message) + "' of message '" + + protoName(message) + "' requires a method '" + method + "' for message '" + protoName(clash) + + "' of '" + source.apply(Util.definingFile(clash)) + "' and for message '" + + protoName(specialization) + "' of '" + source.apply(Util.definingFile(specialization)) + + "'. " + renameHint()); + } + } + } + }); + } + } + + /** + * The name of the given definition qualified with its package and outer messages, as written in + * the .proto file. + */ + private static String protoName(Definition def) { + List names = new ArrayList<>(); + for (Definition current = def; current != null; current = current.getOuter()) { + names.add(0, current.getName()); + } + QName pkg = Util.definingFile(def).getPackage(); + if (pkg != null) { + names.addAll(0, pkg.getNames()); + } + return String.join(".", names); + } + + private static String renameHint() { + return "Rename one of the messages (TypeScript helper names are derived from the message name qualified with" + + " the names of its outer messages, joined with '_', without the package)."; + } + + /** + * Generates the helper declarations for the given top-level definition and its nested + * definitions. + * + *

+ * All helpers are placed at the top level of the module, also for nested definitions: A + * namespace containing values is not erasable TypeScript syntax, only type declarations are + * placed in namespaces. + *

+ */ + private void generateHelpers(Definition def) { + forEachMessage(def, message -> { + if (hasPolymorphicType(message)) { + generateVisitor(message); + generateDispatch(message); + generateGuard(message); + } + if (isTagged(message)) { + generateTag(message); + } + }); + } + + private void generateVisitor(MessageDef def) { + List specializations = Util.concreteTransitiveSpecializations(def); + boolean open = isOpen(def); + String type = ref(def, null); + + separate(); + String comment = "Handlers for all concrete types of {@link " + type + "}."; + if (open) { + comment += "\n\nThe hierarchy is open (option OpenWorld), a type not known to this module is handled by {@link " + + visitorName(def) + ".visitDefault}."; + } + docComment(comment); + if (specializations.isEmpty() && !open) { + line("export interface " + visitorName(def) + " {}"); + return; + } + line("export interface " + visitorName(def) + " {"); + boolean first = true; + for (MessageDef specialization : specializations) { + if (first) { + first = false; + } else { + nl(); + } + String specializationType = ref(specialization, null); + docComment("Handles a {@link " + specializationType + "}."); + line("" + visitMethodName(specialization) + "(self: " + specializationType + "): R;"); + } + if (open) { + if (!first) { + nl(); + } + docComment("Handles a type that is not known to this module, e.g. an extension defined in another module.\n\n" + + "@param self - The properties of the value.\n" + + "@param typeId - The type ID of the value."); + line("visitDefault(self: " + type + ", typeId: string): R;"); + } + line("}"); + } + + private void generateDispatch(MessageDef def) { + boolean open = isOpen(def); + separate(); + docComment("Dispatches a type-tagged {@link " + polymorphicRef(def, null) + + "} value to the handler of its concrete type.\n\n" + + (open + ? "A type ID not known to this module is dispatched to {@link " + visitorName(def) + ".visitDefault}." + : "@throws Error if the type ID is not known.")); + line("export function " + dispatchName(def) + "(value: " + polymorphicRef(def, null) + ", visitor: " + + visitorName(def) + "): R {"); + line("switch (value[0]) {"); + for (MessageDef specialization : Util.concreteTransitiveSpecializations(def)) { + String self = open ? "value[1] as " + ref(specialization, null) : "value[1]"; + line("case " + stringLiteral(MsgBufJsonProtocol.typeId(specialization)) + ": return visitor." + + visitMethodName(specialization) + "(" + self + ");"); + } + if (open) { + line("default: return visitor.visitDefault(value[1], value[0]);"); + } else { + // A missing case is a compile error: the type ID is not narrowed to never. + line("default: {"); + line("const unknownType: never = value[0];"); + line("throw new Error('Unknown type ID: ' + unknownType);"); + line("}"); + } + line("}"); + line("}"); + } + + private void generateGuard(MessageDef def) { + boolean open = isOpen(def); + List specializations = Util.concreteTransitiveSpecializations(def); + String type = polymorphicRef(def, null); + + separate(); + docComment("Checks whether the given value is a type-tagged {@link " + type + "} value: a tuple of a " + + (open ? "type ID" : "known type ID") + " and an object.\n\n" + + "Only the type ID and the shape of the tuple are checked, not the properties of the object."); + line("export function " + guardName(def) + "(value: unknown): value is " + type + " {"); + if (specializations.isEmpty() && !open) { + line("// No concrete type is known."); + line("return false;"); + } else { + String tagCheck; + if (open) { + tagCheck = "typeof value[0] === 'string'"; + } else { + List checks = new ArrayList<>(); + for (MessageDef specialization : specializations) { + checks.add("value[0] === " + stringLiteral(MsgBufJsonProtocol.typeId(specialization))); + } + tagCheck = checks.size() == 1 ? checks.get(0) : "(" + String.join(" || ", checks) + ")"; + } + line("return Array.isArray(value) && value.length === 2"); + line("\t&& " + tagCheck); + line("\t&& typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]);"); + } + line("}"); + } + + private void generateTag(MessageDef def) { + String type = ref(def, null); + String tag = stringLiteral(MsgBufJsonProtocol.typeId(def)); + separate(); + docComment("Creates the type-tagged JSON representation of a {@link " + type + "}."); + line("export function " + tagName(def) + "(self: " + type + "): [" + tag + ", " + type + "] {"); + line("return [" + tag + ", self];"); + line("}"); + } + private String fileComment() { String comment = doc(_proto.getComment(), null); return comment == null || comment.isEmpty() ? "" : comment + "\n\n@packageDocumentation"; diff --git a/de.haumacher.msgbuf.generator/src/test/java/de/haumacher/msgbuf/generator/ts/TestTypeScriptGenerator.java b/de.haumacher.msgbuf.generator/src/test/java/de/haumacher/msgbuf/generator/ts/TestTypeScriptGenerator.java index 22057caa..5a38d758 100644 --- a/de.haumacher.msgbuf.generator/src/test/java/de/haumacher/msgbuf/generator/ts/TestTypeScriptGenerator.java +++ b/de.haumacher.msgbuf.generator/src/test/java/de/haumacher/msgbuf/generator/ts/TestTypeScriptGenerator.java @@ -8,6 +8,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -15,7 +16,9 @@ import java.util.stream.Stream; import de.haumacher.msgbuf.generator.Generator; +import de.haumacher.msgbuf.generator.GeneratorException; import de.haumacher.msgbuf.generator.GeneratorPlugin; +import de.haumacher.msgbuf.generator.parser.ParseException; import junit.framework.TestCase; /** @@ -36,6 +39,8 @@ public class TestTypeScriptGenerator extends TestCase { private static final File EXPECTED_DIR = new File(BASE, "expected"); + private static final File REJECT_DIR = new File("src/test/resources/reject/ts"); + public void testGolden() throws Exception { File outDir = new File("target/ts-test"); deleteRecursively(outDir.toPath()); @@ -73,6 +78,44 @@ public void testGolden() throws Exception { } } + /** Helper names generated for different messages of a module or hierarchy must not clash. */ + public void testHelperNameClash() throws Exception { + String hint = " Rename one of the messages (TypeScript helper names are derived from the message name qualified with" + + " the names of its outer messages, joined with '_', without the package)."; + assertEquals(Arrays.asList( + "reject/ts/collide/names.proto: The TypeScript visitor 'RootJsonVisitor' of message 'reject.ts.collide.Root' requires a method 'visitA_B' for message 'reject.ts.collide.A_B' of 'reject/ts/collide/names.proto' and for message 'reject.ts.collide.A.B' of 'reject/ts/collide/names.proto'." + hint, + "reject/ts/collide/names.proto: The TypeScript declaration 'tagA_B' is generated for message 'reject.ts.collide.A_B' and for message 'reject.ts.collide.A.B'." + hint), + reject("collide/names.proto")); + } + + /** Visitor method names must be unique in a hierarchy across files. */ + public void testVisitorMethodClashAcrossFiles() throws Exception { + assertEquals(Arrays.asList( + "reject/ts/open/base.proto: The TypeScript visitor 'ShapeJsonVisitor' of message 'reject.ts.open.Shape' requires a method 'visitCircle' for message 'reject.ts.one.Circle' of 'reject/ts/one/one.proto' and for message 'reject.ts.two.Circle' of 'reject/ts/two/two.proto'. Rename one of the messages (TypeScript helper names are derived from the message name qualified with the names of its outer messages, joined with '_', without the package)."), + reject("open/base.proto", "open/one.proto", "open/two.proto")); + } + + private List reject(String... protos) throws IOException, ParseException { + File target = new File("target"); + target.mkdirs(); + File out = Files.createTempDirectory(target.toPath(), getName()).toFile(); + Generator generator = new Generator(); + generator.setOut(new File(out, "java")); + generator.setTypeScriptOut(new File(out, "ts")); + for (String proto : protos) { + generator.load(new File(REJECT_DIR, proto)); + } + try { + generator.generate(GeneratorPlugin.none()); + fail("Expected rejection of " + Arrays.toString(protos) + "."); + return null; + } catch (GeneratorException ex) { + String[] written = out.list(); + assertTrue("No code must be generated for rejected definitions.", written == null || written.length == 0); + return ex.getErrors(); + } + } + private static List protoFiles() throws IOException { try (Stream files = Files.walk(PROTO_DIR.toPath())) { return files diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/collide/names.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/collide/names.proto new file mode 100644 index 00000000..b17d83c8 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/collide/names.proto @@ -0,0 +1,15 @@ +package reject.ts.collide; + +abstract message Root { +} + +/** Helper name part 'A_B'. */ +message A_B extends Root { +} + +message A { + /** Helper name part 'A_B' as well. */ + @Name("A.B") + message B extends Root { + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/base.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/base.proto new file mode 100644 index 00000000..091d4c48 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/base.proto @@ -0,0 +1,6 @@ +package reject.ts.open; + +option OpenWorld; + +abstract message Shape { +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/one.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/one.proto new file mode 100644 index 00000000..0f2ca719 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/one.proto @@ -0,0 +1,6 @@ +package reject.ts.one; + +import "base.proto"; + +message Circle extends reject.ts.open.Shape { +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/two.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/two.proto new file mode 100644 index 00000000..8409a512 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/ts/open/two.proto @@ -0,0 +1,7 @@ +package reject.ts.two; + +import "base.proto"; + +@Name("two.Circle") +message Circle extends reject.ts.open.Shape { +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/commands/commands.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/commands/commands.ts new file mode 100644 index 00000000..6cf31ff5 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/commands/commands.ts @@ -0,0 +1,549 @@ +// Generated by msgbuf from 'test/ts/commands/commands.proto'. Do not edit. +// +// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its +// type-tagged polymorphic values (visitor dispatch, tagging, tag guards). + +/** + * Commands for testing the TypeScript helpers of polymorphic values in a closed hierarchy. + * + * @packageDocumentation + */ + +/** + * Root of a closed hierarchy. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface CommandJson { + /** + * The command ID. + */ + id: string; +} + +/** + * Polymorphic JSON representation of a {@link CommandJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyCommandJson = ['Script', ScriptJson] | ['Batch', BatchJson] | ['Batch.Item', BatchJson.Item] | ['Macro', MacroJson] | ['Insert', InsertJson] | ['delete', deleteJson] | ['Macro.Item', MacroJson.Item] | ['Bold', BoldJson] | ['Replace', ReplaceJson]; + +/** + * Handlers for all concrete types of {@link CommandJson}. + */ +export interface CommandJsonVisitor { + /** + * Handles a {@link ScriptJson}. + */ + visitScript(self: ScriptJson): R; + + /** + * Handles a {@link BatchJson}. + */ + visitBatch(self: BatchJson): R; + + /** + * Handles a {@link BatchJson.Item}. + */ + visitBatch_Item(self: BatchJson.Item): R; + + /** + * Handles a {@link MacroJson}. + */ + visitMacro(self: MacroJson): R; + + /** + * Handles a {@link InsertJson}. + */ + visitInsert(self: InsertJson): R; + + /** + * Handles a {@link deleteJson}. + */ + visitDelete(self: deleteJson): R; + + /** + * Handles a {@link MacroJson.Item}. + */ + visitMacro_Item(self: MacroJson.Item): R; + + /** + * Handles a {@link BoldJson}. + */ + visitBold(self: BoldJson): R; + + /** + * Handles a {@link ReplaceJson}. + */ + visitReplace(self: ReplaceJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyCommandJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitCommandJson(value: AnyCommandJson, visitor: CommandJsonVisitor): R { + switch (value[0]) { + case 'Script': return visitor.visitScript(value[1]); + case 'Batch': return visitor.visitBatch(value[1]); + case 'Batch.Item': return visitor.visitBatch_Item(value[1]); + case 'Macro': return visitor.visitMacro(value[1]); + case 'Insert': return visitor.visitInsert(value[1]); + case 'delete': return visitor.visitDelete(value[1]); + case 'Macro.Item': return visitor.visitMacro_Item(value[1]); + case 'Bold': return visitor.visitBold(value[1]); + case 'Replace': return visitor.visitReplace(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyCommandJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyCommandJson(value: unknown): value is AnyCommandJson { + return Array.isArray(value) && value.length === 2 + && (value[0] === 'Script' || value[0] === 'Batch' || value[0] === 'Batch.Item' || value[0] === 'Macro' || value[0] === 'Insert' || value[0] === 'delete' || value[0] === 'Macro.Item' || value[0] === 'Bold' || value[0] === 'Replace') + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * Abstract intermediate at level two. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface EditJson extends CommandJson { + /** + * The edited element. + */ + target: string; +} + +/** + * Polymorphic JSON representation of a {@link EditJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyEditJson = ['Insert', InsertJson] | ['delete', deleteJson] | ['Macro.Item', MacroJson.Item] | ['Bold', BoldJson] | ['Replace', ReplaceJson]; + +/** + * Handlers for all concrete types of {@link EditJson}. + */ +export interface EditJsonVisitor { + /** + * Handles a {@link InsertJson}. + */ + visitInsert(self: InsertJson): R; + + /** + * Handles a {@link deleteJson}. + */ + visitDelete(self: deleteJson): R; + + /** + * Handles a {@link MacroJson.Item}. + */ + visitMacro_Item(self: MacroJson.Item): R; + + /** + * Handles a {@link BoldJson}. + */ + visitBold(self: BoldJson): R; + + /** + * Handles a {@link ReplaceJson}. + */ + visitReplace(self: ReplaceJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyEditJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitEditJson(value: AnyEditJson, visitor: EditJsonVisitor): R { + switch (value[0]) { + case 'Insert': return visitor.visitInsert(value[1]); + case 'delete': return visitor.visitDelete(value[1]); + case 'Macro.Item': return visitor.visitMacro_Item(value[1]); + case 'Bold': return visitor.visitBold(value[1]); + case 'Replace': return visitor.visitReplace(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyEditJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyEditJson(value: unknown): value is AnyEditJson { + return Array.isArray(value) && value.length === 2 + && (value[0] === 'Insert' || value[0] === 'delete' || value[0] === 'Macro.Item' || value[0] === 'Bold' || value[0] === 'Replace') + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * Abstract intermediate at level three. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface StyledEditJson extends EditJson { + /** + * The style to apply. + */ + style: string; +} + +/** + * Polymorphic JSON representation of a {@link StyledEditJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyStyledEditJson = ['Bold', BoldJson]; + +/** + * Handlers for all concrete types of {@link StyledEditJson}. + */ +export interface StyledEditJsonVisitor { + /** + * Handles a {@link BoldJson}. + */ + visitBold(self: BoldJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyStyledEditJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitStyledEditJson(value: AnyStyledEditJson, visitor: StyledEditJsonVisitor): R { + switch (value[0]) { + case 'Bold': return visitor.visitBold(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyStyledEditJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyStyledEditJson(value: unknown): value is AnyStyledEditJson { + return Array.isArray(value) && value.length === 2 + && value[0] === 'Bold' + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * A concrete edit at level three. + */ +export interface InsertJson extends EditJson { + text: string; +} + +/** + * Creates the type-tagged JSON representation of a {@link InsertJson}. + */ +export function tagInsert(self: InsertJson): ['Insert', InsertJson] { + return ['Insert', self]; +} + +/** + * A concrete type specializing a concrete type. + */ +export interface ReplaceJson extends InsertJson { + length: number; +} + +/** + * Creates the type-tagged JSON representation of a {@link ReplaceJson}. + */ +export function tagReplace(self: ReplaceJson): ['Replace', ReplaceJson] { + return ['Replace', self]; +} + +/** + * A concrete edit at level four. + */ +export interface BoldJson extends StyledEditJson {} + +/** + * Creates the type-tagged JSON representation of a {@link BoldJson}. + */ +export function tagBold(self: BoldJson): ['Bold', BoldJson] { + return ['Bold', self]; +} + +/** + * A message whose name is a reserved word in TypeScript. + */ +export interface deleteJson extends EditJson { + count: number; +} + +/** + * Creates the type-tagged JSON representation of a {@link deleteJson}. + */ +export function tagDelete(self: deleteJson): ['delete', deleteJson] { + return ['delete', self]; +} + +/** + * A message with polymorphic collections. + */ +export interface ScriptJson extends CommandJson { + /** + * A polymorphic list. + */ + steps: AnyCommandJson[]; + + /** + * A polymorphic map. + */ + named: Record; + + /** + * A polymorphic map with a key that is not a string. + */ + numbered: Array<{ key: number; value: AnyEditJson }>; + + /** + * An optional polymorphic value of an intermediate. + */ + style?: AnyStyledEditJson; +} + +/** + * Creates the type-tagged JSON representation of a {@link ScriptJson}. + */ +export function tagScript(self: ScriptJson): ['Script', ScriptJson] { + return ['Script', self]; +} + +/** + * Container of a nested message named like one in {@link MacroJson}. + */ +export interface BatchJson extends CommandJson { + /** + * Monomorphic references. + */ + items: BatchJson.Item[]; +} + +export namespace BatchJson { + /** + * Nested specialization of the root. + */ + export interface Item extends CommandJson { + note: string; + } +} + +/** + * Creates the type-tagged JSON representation of a {@link BatchJson}. + */ +export function tagBatch(self: BatchJson): ['Batch', BatchJson] { + return ['Batch', self]; +} + +/** + * Creates the type-tagged JSON representation of a {@link BatchJson.Item}. + */ +export function tagBatch_Item(self: BatchJson.Item): ['Batch.Item', BatchJson.Item] { + return ['Batch.Item', self]; +} + +/** + * Container of a nested message named like one in {@link BatchJson}, and of a nested hierarchy. + */ +export interface MacroJson extends CommandJson { + /** + * Steps of the nested hierarchy. + */ + steps: MacroJson.AnyStep[]; + + /** + * Items of the intermediate. + */ + edits: AnyEditJson[]; +} + +export namespace MacroJson { + /** + * Nested specialization of an intermediate. + */ + export interface Item extends EditJson { + repeat: number; + } + + /** + * Root of a nested hierarchy. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ + export interface Step {} + + /** + * Polymorphic JSON representation of a {@link Step}: a tuple of the type ID and the properties of a concrete type. + */ + export type AnyStep = ['Wait', MacroJson.Wait] | ['Group.Wait', MacroJson.Group.Wait]; + + /** + * Specialization in the nested hierarchy. + */ + export interface Wait extends MacroJson.Step { + millis: number; + } + + /** + * Specialization in the nested hierarchy nested in another nested message. + */ + export interface Group {} + + export namespace Group { + /** + * Needs a type ID different from the one of {@link MacroJson.Wait}. + */ + export interface Wait extends MacroJson.Step { + count: number; + } + } +} + +/** + * Creates the type-tagged JSON representation of a {@link MacroJson}. + */ +export function tagMacro(self: MacroJson): ['Macro', MacroJson] { + return ['Macro', self]; +} + +/** + * Creates the type-tagged JSON representation of a {@link MacroJson.Item}. + */ +export function tagMacro_Item(self: MacroJson.Item): ['Macro.Item', MacroJson.Item] { + return ['Macro.Item', self]; +} + +/** + * Handlers for all concrete types of {@link MacroJson.Step}. + */ +export interface Macro_StepJsonVisitor { + /** + * Handles a {@link MacroJson.Wait}. + */ + visitMacro_Wait(self: MacroJson.Wait): R; + + /** + * Handles a {@link MacroJson.Group.Wait}. + */ + visitMacro_Group_Wait(self: MacroJson.Group.Wait): R; +} + +/** + * Dispatches a type-tagged {@link MacroJson.AnyStep} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitMacro_StepJson(value: MacroJson.AnyStep, visitor: Macro_StepJsonVisitor): R { + switch (value[0]) { + case 'Wait': return visitor.visitMacro_Wait(value[1]); + case 'Group.Wait': return visitor.visitMacro_Group_Wait(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link MacroJson.AnyStep} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyMacro_StepJson(value: unknown): value is MacroJson.AnyStep { + return Array.isArray(value) && value.length === 2 + && (value[0] === 'Wait' || value[0] === 'Group.Wait') + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * Creates the type-tagged JSON representation of a {@link MacroJson.Wait}. + */ +export function tagMacro_Wait(self: MacroJson.Wait): ['Wait', MacroJson.Wait] { + return ['Wait', self]; +} + +/** + * Creates the type-tagged JSON representation of a {@link MacroJson.Group.Wait}. + */ +export function tagMacro_Group_Wait(self: MacroJson.Group.Wait): ['Group.Wait', MacroJson.Group.Wait] { + return ['Group.Wait', self]; +} + +/** + * An abstract root without concrete types. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface EmptyJson {} + +/** + * Polymorphic JSON representation of a {@link EmptyJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyEmptyJson = never; + +/** + * Handlers for all concrete types of {@link EmptyJson}. + */ +export interface EmptyJsonVisitor {} + +/** + * Dispatches a type-tagged {@link AnyEmptyJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitEmptyJson(value: AnyEmptyJson, visitor: EmptyJsonVisitor): R { + switch (value[0]) { + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyEmptyJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyEmptyJson(value: unknown): value is AnyEmptyJson { + // No concrete type is known. + return false; +} + +/** + * Concrete root of a hierarchy without type tags: no helpers. + */ +export interface PlainJson { + name: string; +} + +/** + * Specialization of a concrete root: no helpers. + */ +export interface FancyJson extends PlainJson { + color: string; +} + +/** + * An abstract message below a concrete root: no helpers. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface AbstractedJson extends PlainJson {} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/common/common.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/common/common.ts index b6b3f720..cf9c5b6c 100644 --- a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/common/common.ts +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/common/common.ts @@ -1,6 +1,7 @@ // Generated by msgbuf from 'test/ts/common/common.proto'. Do not edit. // -// Type definitions for the msgbuf JSON format of the protocol (types only, no runtime code). +// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its +// type-tagged polymorphic values (visitor dispatch, tagging, tag guards). /** * Common types, documented at the package declaration. @@ -57,6 +58,48 @@ export interface NodeJson { */ export type AnyNodeJson = ['Leaf', LeafJson] | ['Inner', InnerJson]; +/** + * Handlers for all concrete types of {@link NodeJson}. + */ +export interface NodeJsonVisitor { + /** + * Handles a {@link LeafJson}. + */ + visitLeaf(self: LeafJson): R; + + /** + * Handles a {@link InnerJson}. + */ + visitInner(self: InnerJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyNodeJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitNodeJson(value: AnyNodeJson, visitor: NodeJsonVisitor): R { + switch (value[0]) { + case 'Leaf': return visitor.visitLeaf(value[1]); + case 'Inner': return visitor.visitInner(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyNodeJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyNodeJson(value: unknown): value is AnyNodeJson { + return Array.isArray(value) && value.length === 2 + && (value[0] === 'Leaf' || value[0] === 'Inner') + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + /** * A leaf node. */ @@ -67,6 +110,13 @@ export interface LeafJson extends NodeJson { value: number; } +/** + * Creates the type-tagged JSON representation of a {@link LeafJson}. + */ +export function tagLeaf(self: LeafJson): ['Leaf', LeafJson] { + return ['Leaf', self]; +} + /** * An inner node. */ @@ -76,3 +126,10 @@ export interface InnerJson extends NodeJson { */ children: AnyNodeJson[]; } + +/** + * Creates the type-tagged JSON representation of a {@link InnerJson}. + */ +export function tagInner(self: InnerJson): ['Inner', InnerJson] { + return ['Inner', self]; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/base/base.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/base/base.ts new file mode 100644 index 00000000..dc61df41 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/base/base.ts @@ -0,0 +1,197 @@ +// Generated by msgbuf from 'test/ts/events/base/base.proto'. Do not edit. +// +// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its +// type-tagged polymorphic values (visitor dispatch, tagging, tag guards). + +/** + * An OpenWorld hierarchy extended in another file. + * + * @packageDocumentation + */ + +import type { OuterJson, RemoveJson, AlertJson } from '../ext/ext'; + +/** + * Root of an open hierarchy. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface EventJson { + /** + * Time of the event. + */ + timestamp: number; +} + +/** + * Polymorphic JSON representation of a {@link EventJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyEventJson = ['Ping', PingJson] | ['Outer.Ping', OuterJson.Ping] | ['set', UpdateJson] | ['Remove', RemoveJson] | ['Alert', AlertJson] | [string, EventJson]; + +/** + * Handlers for all concrete types of {@link EventJson}. + * + * The hierarchy is open (option OpenWorld), a type not known to this module is handled by {@link EventJsonVisitor.visitDefault}. + */ +export interface EventJsonVisitor { + /** + * Handles a {@link PingJson}. + */ + visitPing(self: PingJson): R; + + /** + * Handles a {@link OuterJson.Ping}. + */ + visitOuter_Ping(self: OuterJson.Ping): R; + + /** + * Handles a {@link UpdateJson}. + */ + visitUpdate(self: UpdateJson): R; + + /** + * Handles a {@link RemoveJson}. + */ + visitRemove(self: RemoveJson): R; + + /** + * Handles a {@link AlertJson}. + */ + visitAlert(self: AlertJson): R; + + /** + * Handles a type that is not known to this module, e.g. an extension defined in another module. + * + * @param self - The properties of the value. + * @param typeId - The type ID of the value. + */ + visitDefault(self: EventJson, typeId: string): R; +} + +/** + * Dispatches a type-tagged {@link AnyEventJson} value to the handler of its concrete type. + * + * A type ID not known to this module is dispatched to {@link EventJsonVisitor.visitDefault}. + */ +export function visitEventJson(value: AnyEventJson, visitor: EventJsonVisitor): R { + switch (value[0]) { + case 'Ping': return visitor.visitPing(value[1] as PingJson); + case 'Outer.Ping': return visitor.visitOuter_Ping(value[1] as OuterJson.Ping); + case 'set': return visitor.visitUpdate(value[1] as UpdateJson); + case 'Remove': return visitor.visitRemove(value[1] as RemoveJson); + case 'Alert': return visitor.visitAlert(value[1] as AlertJson); + default: return visitor.visitDefault(value[1], value[0]); + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyEventJson} value: a tuple of a type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyEventJson(value: unknown): value is AnyEventJson { + return Array.isArray(value) && value.length === 2 + && typeof value[0] === 'string' + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * A local concrete type. + */ +export interface PingJson extends EventJson {} + +/** + * Creates the type-tagged JSON representation of a {@link PingJson}. + */ +export function tagPing(self: PingJson): ['Ping', PingJson] { + return ['Ping', self]; +} + +/** + * An abstract intermediate, extended in another file. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface ChangeJson extends EventJson { + /** + * The changed key. + */ + key: string; +} + +/** + * Polymorphic JSON representation of a {@link ChangeJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyChangeJson = ['set', UpdateJson] | ['Remove', RemoveJson] | [string, ChangeJson]; + +/** + * Handlers for all concrete types of {@link ChangeJson}. + * + * The hierarchy is open (option OpenWorld), a type not known to this module is handled by {@link ChangeJsonVisitor.visitDefault}. + */ +export interface ChangeJsonVisitor { + /** + * Handles a {@link UpdateJson}. + */ + visitUpdate(self: UpdateJson): R; + + /** + * Handles a {@link RemoveJson}. + */ + visitRemove(self: RemoveJson): R; + + /** + * Handles a type that is not known to this module, e.g. an extension defined in another module. + * + * @param self - The properties of the value. + * @param typeId - The type ID of the value. + */ + visitDefault(self: ChangeJson, typeId: string): R; +} + +/** + * Dispatches a type-tagged {@link AnyChangeJson} value to the handler of its concrete type. + * + * A type ID not known to this module is dispatched to {@link ChangeJsonVisitor.visitDefault}. + */ +export function visitChangeJson(value: AnyChangeJson, visitor: ChangeJsonVisitor): R { + switch (value[0]) { + case 'set': return visitor.visitUpdate(value[1] as UpdateJson); + case 'Remove': return visitor.visitRemove(value[1] as RemoveJson); + default: return visitor.visitDefault(value[1], value[0]); + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyChangeJson} value: a tuple of a type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyChangeJson(value: unknown): value is AnyChangeJson { + return Array.isArray(value) && value.length === 2 + && typeof value[0] === 'string' + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * A local concrete type of the intermediate. + */ +export interface UpdateJson extends ChangeJson { + value: string; +} + +/** + * Creates the type-tagged JSON representation of a {@link UpdateJson}. + */ +export function tagUpdate(self: UpdateJson): ['set', UpdateJson] { + return ['set', self]; +} + +/** + * Polymorphic collections of the open hierarchy. + */ +export interface LogJson { + events: AnyEventJson[]; + + latest: Record; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/ext/ext.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/ext/ext.ts new file mode 100644 index 00000000..e1b745fe --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/events/ext/ext.ts @@ -0,0 +1,116 @@ +// Generated by msgbuf from 'test/ts/events/ext/ext.proto'. Do not edit. +// +// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its +// type-tagged polymorphic values (visitor dispatch, tagging, tag guards). + +/** + * Extensions of the OpenWorld hierarchy of another file. + * + * @packageDocumentation + */ + +import type { ChangeJson, EventJson } from '../base/base'; + +/** + * Specialization of the intermediate of another file. + */ +export interface RemoveJson extends ChangeJson {} + +/** + * Creates the type-tagged JSON representation of a {@link RemoveJson}. + */ +export function tagRemove(self: RemoveJson): ['Remove', RemoveJson] { + return ['Remove', self]; +} + +/** + * An abstract intermediate of the extension file. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface NoticeJson extends EventJson { + text: string; +} + +/** + * Polymorphic JSON representation of a {@link NoticeJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyNoticeJson = ['Alert', AlertJson] | [string, NoticeJson]; + +/** + * Handlers for all concrete types of {@link NoticeJson}. + * + * The hierarchy is open (option OpenWorld), a type not known to this module is handled by {@link NoticeJsonVisitor.visitDefault}. + */ +export interface NoticeJsonVisitor { + /** + * Handles a {@link AlertJson}. + */ + visitAlert(self: AlertJson): R; + + /** + * Handles a type that is not known to this module, e.g. an extension defined in another module. + * + * @param self - The properties of the value. + * @param typeId - The type ID of the value. + */ + visitDefault(self: NoticeJson, typeId: string): R; +} + +/** + * Dispatches a type-tagged {@link AnyNoticeJson} value to the handler of its concrete type. + * + * A type ID not known to this module is dispatched to {@link NoticeJsonVisitor.visitDefault}. + */ +export function visitNoticeJson(value: AnyNoticeJson, visitor: NoticeJsonVisitor): R { + switch (value[0]) { + case 'Alert': return visitor.visitAlert(value[1] as AlertJson); + default: return visitor.visitDefault(value[1], value[0]); + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyNoticeJson} value: a tuple of a type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyNoticeJson(value: unknown): value is AnyNoticeJson { + return Array.isArray(value) && value.length === 2 + && typeof value[0] === 'string' + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + +/** + * Specialization of the local intermediate. + */ +export interface AlertJson extends NoticeJson { + level: number; +} + +/** + * Creates the type-tagged JSON representation of a {@link AlertJson}. + */ +export function tagAlert(self: AlertJson): ['Alert', AlertJson] { + return ['Alert', self]; +} + +/** + * Outer message of a nested extension. + */ +export interface OuterJson { + notices: AnyNoticeJson[]; +} + +export namespace OuterJson { + /** + * A nested extension named like a type of the base file. + */ + export interface Ping extends EventJson {} +} + +/** + * Creates the type-tagged JSON representation of a {@link OuterJson.Ping}. + */ +export function tagOuter_Ping(self: OuterJson.Ping): ['Outer.Ping', OuterJson.Ping] { + return ['Outer.Ping', self]; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/graph/graph.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/graph/graph.ts new file mode 100644 index 00000000..97748ffd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/graph/graph.ts @@ -0,0 +1,28 @@ +// Generated by msgbuf from 'test/ts/graph/graph.proto'. Do not edit. +// +// Type definitions for the msgbuf JSON format of the protocol (types only, no runtime code). +// +// Note: The protocol uses 'option SharedGraph'. Its JSON format (objects as [type, id, {...}], +// references as object IDs, incremental updates) is not described by these types. No helper +// functions for polymorphic values are generated. + +/** + * Root of a hierarchy of a shared graph: no helpers. + * + * Abstract type, the properties are only present in the JSON of its concrete specializations. + */ +export interface ElementJson { + name: string; +} + +/** + * Polymorphic JSON representation of a {@link ElementJson}: a tuple of the type ID and the properties of a concrete type. + */ +export type AnyElementJson = ['Vertex', VertexJson]; + +/** + * A concrete element. + */ +export interface VertexJson extends ElementJson { + children: AnyElementJson[]; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/shapes/shapes.ts b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/shapes/shapes.ts index 7c98da66..b484d553 100644 --- a/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/shapes/shapes.ts +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/expected/test/ts/shapes/shapes.ts @@ -1,6 +1,7 @@ // Generated by msgbuf from 'test/ts/shapes/shapes.proto'. Do not edit. // -// Type definitions for the msgbuf JSON format of the protocol (types only, no runtime code). +// Type definitions for the msgbuf JSON format of the protocol, and helper functions for its +// type-tagged polymorphic values (visitor dispatch, tagging, tag guards). /** * Shapes and button states for testing the TypeScript generator. @@ -153,6 +154,54 @@ export interface ShapeJson { */ export type AnyShapeJson = ['Rectangle', RectangleJson] | ['Group', GroupJson] | ['circle', CircleJson]; +/** + * Handlers for all concrete types of {@link ShapeJson}. + */ +export interface ShapeJsonVisitor { + /** + * Handles a {@link RectangleJson}. + */ + visitRectangle(self: RectangleJson): R; + + /** + * Handles a {@link GroupJson}. + */ + visitGroup(self: GroupJson): R; + + /** + * Handles a {@link CircleJson}. + */ + visitCircle(self: CircleJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyShapeJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitShapeJson(value: AnyShapeJson, visitor: ShapeJsonVisitor): R { + switch (value[0]) { + case 'Rectangle': return visitor.visitRectangle(value[1]); + case 'Group': return visitor.visitGroup(value[1]); + case 'circle': return visitor.visitCircle(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyShapeJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyShapeJson(value: unknown): value is AnyShapeJson { + return Array.isArray(value) && value.length === 2 + && (value[0] === 'Rectangle' || value[0] === 'Group' || value[0] === 'circle') + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + /** * Abstract intermediate class. * @@ -165,6 +214,42 @@ export interface RoundedJson extends ShapeJson {} */ export type AnyRoundedJson = ['circle', CircleJson]; +/** + * Handlers for all concrete types of {@link RoundedJson}. + */ +export interface RoundedJsonVisitor { + /** + * Handles a {@link CircleJson}. + */ + visitCircle(self: CircleJson): R; +} + +/** + * Dispatches a type-tagged {@link AnyRoundedJson} value to the handler of its concrete type. + * + * @throws Error if the type ID is not known. + */ +export function visitRoundedJson(value: AnyRoundedJson, visitor: RoundedJsonVisitor): R { + switch (value[0]) { + case 'circle': return visitor.visitCircle(value[1]); + default: { + const unknownType: never = value[0]; + throw new Error('Unknown type ID: ' + unknownType); + } + } +} + +/** + * Checks whether the given value is a type-tagged {@link AnyRoundedJson} value: a tuple of a known type ID and an object. + * + * Only the type ID and the shape of the tuple are checked, not the properties of the object. + */ +export function isAnyRoundedJson(value: unknown): value is AnyRoundedJson { + return Array.isArray(value) && value.length === 2 + && value[0] === 'circle' + && typeof value[1] === 'object' && value[1] !== null && !Array.isArray(value[1]); +} + /** * A circle. */ @@ -175,6 +260,13 @@ export interface CircleJson extends RoundedJson { r: number; } +/** + * Creates the type-tagged JSON representation of a {@link CircleJson}. + */ +export function tagCircle(self: CircleJson): ['circle', CircleJson] { + return ['circle', self]; +} + /** * A rectangle. */ @@ -184,6 +276,13 @@ export interface RectangleJson extends ShapeJson { height: number; } +/** + * Creates the type-tagged JSON representation of a {@link RectangleJson}. + */ +export function tagRectangle(self: RectangleJson): ['Rectangle', RectangleJson] { + return ['Rectangle', self]; +} + /** * A group of shapes. */ @@ -244,6 +343,13 @@ export namespace GroupJson { } } +/** + * Creates the type-tagged JSON representation of a {@link GroupJson}. + */ +export function tagGroup(self: GroupJson): ['Group', GroupJson] { + return ['Group', self]; +} + /** * An empty enum. */ diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/commands/commands.proto b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/commands/commands.proto new file mode 100644 index 00000000..62751f42 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/commands/commands.proto @@ -0,0 +1,127 @@ +/** + * Commands for testing the TypeScript helpers of polymorphic values in a closed hierarchy. + */ +syntax = "msgbuf"; + +package test.ts.commands; + +option NoXml; + +/* The Java TypeKind enums would contain the constants ITEM and WAIT twice (nested messages with equal names). */ +option NoTypeKind; + +/** Root of a closed hierarchy. */ +abstract message Command { + /** The command ID. */ + string id; +} + +/** Abstract intermediate at level two. */ +abstract message Edit extends Command { + /** The edited element. */ + string target; +} + +/** Abstract intermediate at level three. */ +abstract message StyledEdit extends Edit { + /** The style to apply. */ + string style; +} + +/** A concrete edit at level three. */ +message Insert extends Edit { + string text; +} + +/** A concrete type specializing a concrete type. */ +message Replace extends Insert { + int32 length; +} + +/** A concrete edit at level four. */ +message Bold extends StyledEdit { +} + +/** A message whose name is a reserved word in TypeScript. */ +message `delete` extends Edit { + int32 count; +} + +/** A message with polymorphic collections. */ +message Script extends Command { + /** A polymorphic list. */ + repeated Command steps; + + /** A polymorphic map. */ + map named; + + /** A polymorphic map with a key that is not a string. */ + map numbered; + + /** An optional polymorphic value of an intermediate. */ + @Nullable + StyledEdit style; +} + +/** Container of a nested message named like one in {@link Macro}. */ +message Batch extends Command { + /** Nested specialization of the root. */ + @Name("Batch.Item") + message Item extends Command { + string note; + } + + /** Monomorphic references. */ + repeated Item items; +} + +/** Container of a nested message named like one in {@link Batch}, and of a nested hierarchy. */ +message Macro extends Command { + /** Nested specialization of an intermediate. */ + @Name("Macro.Item") + message Item extends Edit { + int32 repeat; + } + + /** Root of a nested hierarchy. */ + abstract message Step { + } + + /** Specialization in the nested hierarchy. */ + message Wait extends Step { + int32 millis; + } + + /** Specialization in the nested hierarchy nested in another nested message. */ + message Group { + /** Needs a type ID different from the one of {@link Macro.Wait}. */ + @Name("Group.Wait") + message Wait extends Step { + int32 count; + } + } + + /** Steps of the nested hierarchy. */ + repeated Step steps; + + /** Items of the intermediate. */ + repeated Edit edits; +} + +/** An abstract root without concrete types. */ +abstract message Empty { +} + +/** Concrete root of a hierarchy without type tags: no helpers. */ +message Plain { + string name; +} + +/** Specialization of a concrete root: no helpers. */ +message Fancy extends Plain { + string color; +} + +/** An abstract message below a concrete root: no helpers. */ +abstract message Abstracted extends Plain { +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/base/base.proto b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/base/base.proto new file mode 100644 index 00000000..5b89db8f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/base/base.proto @@ -0,0 +1,40 @@ +/** + * An OpenWorld hierarchy extended in another file. + */ +syntax = "msgbuf"; + +package test.ts.events.base; + +option OpenWorld; + +/* Maps are not supported in XML. */ +option NoXml; + +/** Root of an open hierarchy. */ +abstract message Event { + /** Time of the event. */ + int64 timestamp; +} + +/** A local concrete type. */ +message Ping extends Event { +} + +/** An abstract intermediate, extended in another file. */ +abstract message Change extends Event { + /** The changed key. */ + string key; +} + +/** A local concrete type of the intermediate. */ +@Name("set") +message Update extends Change { + string value; +} + +/** Polymorphic collections of the open hierarchy. */ +message Log { + repeated Event events; + + map latest; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/ext/ext.proto b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/ext/ext.proto new file mode 100644 index 00000000..8372ad71 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/events/ext/ext.proto @@ -0,0 +1,35 @@ +/** + * Extensions of the OpenWorld hierarchy of another file. + */ +syntax = "msgbuf"; + +package test.ts.events.ext; + +import "../base/base.proto"; + +/* Same format options as the base file. */ +option NoXml; + +/** Specialization of the intermediate of another file. */ +message Remove extends test.ts.events.base.Change { +} + +/** An abstract intermediate of the extension file. */ +abstract message Notice extends test.ts.events.base.Event { + string text; +} + +/** Specialization of the local intermediate. */ +message Alert extends Notice { + int32 level; +} + +/** Outer message of a nested extension. */ +message Outer { + /** A nested extension named like a type of the base file. */ + @Name("Outer.Ping") + message Ping extends test.ts.events.base.Event { + } + + repeated Notice notices; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/graph/graph.proto b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/graph/graph.proto new file mode 100644 index 00000000..d78b927b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/ts/proto/test/ts/graph/graph.proto @@ -0,0 +1,15 @@ +syntax = "msgbuf"; + +package test.ts.graph; + +option SharedGraph; + +/** Root of a hierarchy of a shared graph: no helpers. */ +abstract message Element { + string name; +} + +/** A concrete element. */ +message Vertex extends Element { + repeated Element children; +} From e392a604d5af2cbb3bde9b0150586cc06a8de3b3 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 18:49:10 +0200 Subject: [PATCH 16/20] Fix uncompilable XML primitives, reject clashing type IDs and resolve names by package and imports. Reviewing the TypeScript helpers of #10 turned up three generator bugs that produced uncompilable or silently wrong code. The XML templates for bytes, fixed32 and uint32 did not compile since 1.1.0 (#44); auditing them also fixed null values and empty lists in XML, a binary writer that ignored the zig-zag and fixed-length encodings its own readers expected, and a 64 bit varint decoding bug in msgbuf-api. Messages of one hierarchy with equal type IDs, XML names or TypeKind constants, or named like a nested type of a generalization, generated duplicate cases and constants and are now rejected with an error naming both definitions (#45). Unqualified type names were looked up in one global table where the last loaded file won, so a file's meaning depended on unrelated files generated in the same run; they now resolve in the own package, then the imported files by import depth, and only then in the unique definition of any other file, and duplicate definitions stop the generation (#46). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 31 + README.md | 19 + .../msgbuf/generator/CodeConvention.java | 37 +- .../haumacher/msgbuf/generator/Generator.java | 239 ++- .../msgbuf/generator/GeneratorPlugin.java | 27 + .../msgbuf/generator/MessageGenerator.java | 28 +- .../haumacher/msgbuf/generator/NameTable.java | 242 ++- .../msgbuf/generator/common/Util.java | 29 + .../generator/plugins/XmlStreamingPlugin.java | 58 +- .../generator/ts/TypeScriptGenerator.java | 13 +- .../hierarchynames/TestHierarchyNames.java | 60 + .../test/java/test/hierarchynames/data/A.java | 92 + .../test/java/test/hierarchynames/data/B.java | 92 + .../test/hierarchynames/data/Container.java | 78 + .../java/test/hierarchynames/data/Item.java | 55 + .../java/test/hierarchynames/data/Msg.java | 64 + .../java/test/hierarchynames/data/Outer.java | 155 ++ .../test/hierarchynames/data/impl/A_Impl.java | 353 ++++ .../test/hierarchynames/data/impl/B_Impl.java | 353 ++++ .../data/impl/Container_Impl.java | 318 +++ .../hierarchynames/data/impl/Item_Impl.java | 188 ++ .../hierarchynames/data/impl/Msg_Impl.java | 164 ++ .../hierarchynames/data/impl/Outer_Impl.java | 579 ++++++ .../test/hierarchynames/hierarchynames.proto | 43 + .../nested/data/impl/SearchResponse_Impl.java | 5 +- .../java/test/nested/data/impl/Zoo_Impl.java | 5 +- .../data/impl/NullableValues_Impl.java | 38 +- .../test/validation/TestHierarchyClashes.java | 127 ++ .../test/validation/TestNameResolution.java | 180 ++ .../test/xmlprimitives/TestXmlPrimitives.java | 264 +++ .../java/test/xmlprimitives/data/Color.java | 64 + .../java/test/xmlprimitives/data/Lists.java | 413 ++++ .../test/xmlprimitives/data/Nullables.java | 463 +++++ .../java/test/xmlprimitives/data/Values.java | 271 +++ .../xmlprimitives/data/impl/Lists_Impl.java | 1800 +++++++++++++++++ .../data/impl/Nullables_Impl.java | 1549 ++++++++++++++ .../xmlprimitives/data/impl/Values_Impl.java | 926 +++++++++ .../test/xmlprimitives/xmlprimitives.proto | 77 + .../resources/reject/hierarchy/issue.proto | 9 + .../reject/hierarchy/open/base.proto | 5 + .../resources/reject/hierarchy/open/one.proto | 5 + .../resources/reject/hierarchy/open/two.proto | 5 + .../resources/reject/hierarchy/protocol.proto | 35 + .../resources/reject/hierarchy/shadow.proto | 18 + .../resources/reject/hierarchy/typekind.proto | 21 + .../src/test/resources/reject/names/a/a.proto | 21 + .../src/test/resources/reject/names/b/b.proto | 5 + .../src/test/resources/reject/names/c/c.proto | 6 + .../test/resources/reject/names/dup/one.proto | 3 + .../resources/reject/names/dup/twice.proto | 5 + .../test/resources/reject/names/dup/two.proto | 3 + .../test/resources/reject/names/imp/lib.proto | 3 + .../resources/reject/names/imp/main.proto | 7 + .../resources/reject/names/imports/a/a.proto | 5 + .../resources/reject/names/imports/b/b.proto | 3 + .../resources/reject/names/imports/c/c.proto | 6 + .../resources/reject/names/imports/d/d.proto | 6 + .../resources/reject/names/imports/e/e.proto | 7 + .../msgbuf/binary/OctetDataReader.java | 2 +- .../msgbuf/binary/TestDataReaderWriter.java | 31 + 60 files changed, 9626 insertions(+), 84 deletions(-) create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/TestHierarchyNames.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/A.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/B.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/Container.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/Item.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/Msg.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/Outer.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/A_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/B_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/Container_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/Item_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/Msg_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/data/impl/Outer_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/hierarchynames/hierarchynames.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/validation/TestHierarchyClashes.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/validation/TestNameResolution.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/TestXmlPrimitives.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Color.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Lists.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Nullables.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Values.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Lists_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Nullables_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Values_Impl.java create mode 100644 de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/xmlprimitives.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/issue.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/base.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/one.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/two.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/protocol.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/shadow.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/typekind.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/a/a.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/b/b.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/c/c.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/one.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/twice.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/two.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/lib.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/main.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/a/a.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/b/b.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/c/c.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/d/d.proto create mode 100644 de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/e/e.proto diff --git a/CHANGELOG.md b/CHANGELOG.md index 51fa9f49..d758e540 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,37 @@ now read the types of other files. The generated registration class (e.g. `Ext1Types`) additionally registers the XML element name of each extension type with the root (`registerXml()`, `XML_REGISTRY`), if the files generate XML. The wire formats are unchanged. +- **Primitive types in XML and binary format** (#44): `bytes`, `fixed32` and `uint32` fields no longer generate + uncompilable XML code (all versions since 1.1.0). `bytes` are written in Base64, `fixed32`/`uint32` as unsigned + decimal (the readers also accept the signed form). Nullable fields that are not set are omitted in XML format, and + `bytes` fields without a value in XML and binary format, instead of failing with a `NullPointerException`. An empty `repeated` + value (written as empty attribute) is read as empty list (before, reading failed for numbers, and a list of strings + contained one empty string). In binary format, `sint32`/`sint64` values are now written zig-zag encoded and + `fixed32`/`sfixed32`/`fixed64`/`sfixed64` values in fixed length, as the readers always expected, and 64 bit values + above 32 bits are read correctly (fix in `msgbuf-api`). **Wire format change:** the binary encoding of these six + types changes; values written before could not be read back correctly (except `0`), and writing a `repeated` field + of these types failed. +- **Clashing type IDs in a hierarchy** (#45): Two concrete specializations of an abstract message with the same type + ID (by default the simple name, e.g. a top-level `Item` and a nested `Msg.Item`, or an equal `@Name`), the same XML + element name, or the same explicit `@type_id`, also in extension files of an `option OpenWorld` hierarchy generated + together, are rejected with an error naming both definitions. So are messages of one hierarchy with the same + `TypeKind` constant (fix: rename, or `option NoTypeKind`), and a message with the name of a nested definition of + one of its generalizations, which the generated class could not refer to. A top-level specialization whose simple + name is shadowed by a nested definition in the scope of its generalization is referenced by its qualified name in + the readers (before, the reader dispatched to the nested definition). **Source compatibility:** these definitions + generated uncompilable code before (or silently wrong readers), except equal type IDs in the `option OpenWorld` + registry of extensions of different files, where the last registered type won. +- **Name resolution across packages** (#46): An unqualified type name resolves (after nested definitions of the + message using it and its outer messages) to a definition of the package of the file using it, then to a definition + of the files it imports (directly, then indirectly), and only then to a definition of any other file generated in + the same run, if it is unique (see README, "Type names and imports"). Before, one global table of simple names was + used, and the definition of the last file loaded won. So the resolution of a file's names no longer depends on + unrelated files generated together, as long as it uses definitions of its own package or its imports. Duplicate + definitions in a package (in one or several files) stop the generation with an error naming the files, instead of + only a message on the console. A file given to the generator twice, or given after it + has been loaded as an import, is loaded only once (and generated). **Source compatibility:** an unqualified name + that is defined in two imported files (at the same import depth), or not in the own package or imports but in + several other files generated together, is now rejected as ambiguous; use a qualified name. ## 1.2.1 diff --git a/README.md b/README.md index 9c550c2a..221e78a0 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,25 @@ message SearchResponse { } ``` +### Type names and imports + +Messages and enums of other `.proto` files are made available with `import "path/to/other.proto";` (resolved relative +to the importing file, then in the include paths, then on the classpath). A type can always be referenced by its +qualified name (`package.Type`, `package.Outer.Inner`). An unqualified name `Type` (or `Type.Inner`) is resolved in +the following order; the first step that finds a definition wins: + +1. A nested definition of the message using the name, or of one of its outer messages (innermost first). +2. A top-level definition of the package of the file using the name (in any file of that package generated in the same + run). +3. A top-level definition of a file imported by that file. If none of the imported files defines the name, the files + they import are searched, and so on. Two definitions found in the same step are an error: use a qualified name. +4. For compatibility, a top-level definition of any other file generated in the same run, if exactly one file defines + the name. Otherwise, the name is rejected as ambiguous. + +Because of step 3, adding an unrelated file to the files generated together (e.g. a new `.proto` file in a Maven +project) does not change how the names of a file resolve, as long as the definitions it uses come from its own package +or its imports. A package must not define a top-level name twice, not even in different files. + ### Transient fields Fields marked with `transient` are not serialized in any format (JSON, binary, XML). They exist only in the in-memory diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java index 46c6abe4..902f54c4 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/CodeConvention.java @@ -279,11 +279,44 @@ public static String jsonTypeConstant(MessageDef def) { } public static String jsonTypeConstantRef(MessageDef def) { - // A nested specialization is not in scope by its simple name in the code of its generalization. - String typeRef = def.getFile() == null ? qTypeName(def) : typeName(def); + String typeRef = simpleNameInScopeOfGeneralizations(def) ? typeName(def) : qTypeName(def); return typeRef + "." + jsonTypeConstant(def); } + /** + * Whether the given message can be referenced by its simple name (the simple name of its + * interface or implementation class) from the generated code of its generalizations. + * + *

+ * A nested specialization is not in scope by its simple name in the code of its generalization. + * A top-level specialization is in scope, unless a nested definition with the same name + * shadows it: a nested definition of a generalization, of one of its outer messages, or of one + * of their generalizations. In these cases, the qualified name must be used. + *

+ */ + public static boolean simpleNameInScopeOfGeneralizations(MessageDef def) { + if (def.getFile() == null) { + return false; + } + String name = def.getName(); + java.util.Set seen = new java.util.HashSet<>(); + for (MessageDef generalization = def.getExtendedDef(); generalization != null && seen.add(generalization); + generalization = generalization.getExtendedDef()) { + for (MessageDef scope = generalization; scope != null; scope = scope.getOuter()) { + java.util.Set seenInherited = new java.util.HashSet<>(); + for (MessageDef inherited = scope; inherited != null && seenInherited.add(inherited); + inherited = inherited.getExtendedDef()) { + for (Definition member : inherited.getDefinitions()) { + if (member.getName().equals(name)) { + return false; + } + } + } + } + } + return true; + } + public static String mkBinaryTypeConstant(MessageDef def) { return allUpperCase(def.getName()) + "__TYPE_ID"; } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java index 63c9180c..9f1fcc1a 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/Generator.java @@ -31,11 +31,13 @@ import de.haumacher.msgbuf.generator.ast.Flag; import de.haumacher.msgbuf.generator.ast.MapType; import de.haumacher.msgbuf.generator.ast.MessageDef; +import de.haumacher.msgbuf.generator.ast.NumberOption; import de.haumacher.msgbuf.generator.ast.Option; import de.haumacher.msgbuf.generator.ast.PrimitiveType; import de.haumacher.msgbuf.generator.ast.QName; import de.haumacher.msgbuf.generator.ast.StringOption; import de.haumacher.msgbuf.generator.ast.Type; +import de.haumacher.msgbuf.generator.common.MsgBufJsonProtocol; import de.haumacher.msgbuf.generator.common.Util; import de.haumacher.msgbuf.generator.dart.DartLibGenerator; import de.haumacher.msgbuf.generator.parser.ParseException; @@ -96,6 +98,7 @@ public class Generator { private List _includePaths = new ArrayList<>(); private ClassLoader _importClassLoader; private Set _loadedFiles = new HashSet<>(); + private Map _fileByPath = new HashMap<>(); private List _importedFiles = new ArrayList<>(); public void setOut(File out) { @@ -138,11 +141,20 @@ public DefinitionFile load(String fileName) throws IOException, ParseException { public DefinitionFile load(File file) throws ParseException, IOException, FileNotFoundException { - _loadedFiles.add(file.getCanonicalPath()); + String canonical = file.getCanonicalPath(); + DefinitionFile loaded = _fileByPath.get(canonical); + if (loaded != null) { + // The same file given twice, or given after being loaded as import of another file: + // Generate code for it, but do not enter its definitions again. + _importedFiles.remove(loaded); + return loaded; + } + _loadedFiles.add(canonical); DefinitionFile content; try (InputStream in = new FileInputStream(file)) { content = load(parse(in)); } + _fileByPath.put(canonical, content); _sourceNames.put(content, file.getName()); resolveImports(content, file); return content; @@ -176,6 +188,11 @@ public void generate(GeneratorPlugin plugin) { } List errors = new ArrayList<>(); + // Duplicate definitions and ambiguous names. + errors.addAll(_table.drainErrors(this::sourceDescription)); + if (!errors.isEmpty()) { + throw new GeneratorException(errors); + } for (DefinitionFile file : _files) { validateOpenWorld(file, errors); } @@ -200,6 +217,7 @@ public void generate(GeneratorPlugin plugin) { validateFormatReferences(file, plugin, errors); } } + validateHierarchyNames(plugin, errors); if (!errors.isEmpty()) { throw new GeneratorException(errors); } @@ -626,6 +644,210 @@ private static List generatedNames(Field field) { return Arrays.asList("suffix:" + CodeConvention.suffix(field), "constant:" + CodeConvention.constant(field)); } + /** + * Rejects messages of a hierarchy whose identifiers in the generated code clash. + * + *
    + *
  • The concrete specializations of an abstract message must have distinct type IDs in all + * generated formats (the JSON type ID, explicit binary type IDs and plug-in identifiers such as + * XML element names). The readers of the abstract message dispatch on these IDs (and the + * registry of an option OpenWorld hierarchy is keyed by them), so equal IDs + * produce duplicate case labels or ambiguous data.
  • + *
  • The concrete messages of a hierarchy must have distinct constants in its + * TypeKind enum, unless option NoTypeKind is given.
  • + *
  • A message must not have the name of a nested definition of one of its generalizations: + * In the generated class of the message, the name of the inherited nested class would shadow + * the name of the class itself.
  • + *
+ * + *

+ * All loaded files are considered, so that a clash of an extension with a message of another + * file of the hierarchy is found. A clash is only reported, if at least one of the messages is + * generated. + *

+ */ + private void validateHierarchyNames(GeneratorPlugin plugin, List errors) { + List messages = new ArrayList<>(); + for (DefinitionFile file : _files) { + for (Definition def : file.getDefinitions()) { + collectMessages(def, messages); + } + } + + Set reported = new HashSet<>(); + for (MessageDef message : messages) { + if (message.isAbstract()) { + validateTypeIds(message, plugin, reported, errors); + } + } + + for (MessageDef message : messages) { + if (message.getExtendedDef() == null && !message.getSpecializations().isEmpty()) { + validateTypeKinds(message, errors); + } + } + + for (MessageDef message : messages) { + if (isGenerated(message)) { + validateInheritedNames(message, errors); + } + } + } + + private static void collectMessages(Definition def, List result) { + if (def instanceof MessageDef) { + MessageDef message = (MessageDef) def; + result.add(message); + for (Definition inner : message.getDefinitions()) { + collectMessages(inner, result); + } + } + } + + private boolean isGenerated(Definition def) { + return !_importedFiles.contains(Util.definingFile(def)); + } + + private void validateTypeIds(MessageDef generalization, GeneratorPlugin plugin, Set reported, List errors) { + List specializations = new ArrayList<>(); + addConcreteSpecializations(generalization, specializations, new HashSet<>()); + List> ids = new ArrayList<>(); + for (MessageDef specialization : specializations) { + ids.add(typeIds(specialization, plugin)); + } + for (int n = 1; n < specializations.size(); n++) { + MessageDef message = specializations.get(n); + for (int m = 0; m < n; m++) { + MessageDef other = specializations.get(m); + if (!isGenerated(message) && !isGenerated(other)) { + continue; + } + List clashes = new ArrayList<>(); + Set annotations = new java.util.LinkedHashSet<>(); + boolean renameHelps = false; + for (Map.Entry entry : ids.get(n).entrySet()) { + if (!entry.getValue().equals(ids.get(m).get(entry.getKey()))) { + continue; + } + java.util.regex.Matcher matcher = TYPE_ID_KIND.matcher(entry.getKey()); + String kind = matcher.matches() ? matcher.group(1) : entry.getKey(); + if (matcher.matches()) { + annotations.add(matcher.group(2)); + } + clashes.add("the same " + kind + " '" + entry.getValue() + "'"); + renameHelps |= !entry.getKey().equals(BINARY_TYPE_ID); + } + if (clashes.isEmpty() || !reported.add(Util.protoName(other) + " " + Util.protoName(message))) { + continue; + } + MessageDef blamed = isGenerated(message) ? message : other; + errors.add(sourceDescription(Util.definingFile(blamed)) + ": In the hierarchy of '" + Util.protoName(generalization) + + "', " + describe(other) + " and " + describe(message) + " have " + + String.join(" and ", clashes) + ", so that the readers of '" + Util.protoName(generalization) + + "' cannot distinguish them. " + + (annotations.isEmpty() ? "Rename one of the messages." + : "Give one of the messages a distinct identifier with " + String.join(" or ", annotations) + + (renameHelps ? ", or rename it." : ".")) + ); + } + } + } + + /** + * Description of a type ID: the kind of identifier and the annotation that sets it. + */ + private static final java.util.regex.Pattern TYPE_ID_KIND = java.util.regex.Pattern.compile("(.*) \\((@\\w+)\\)"); + + private static final String BINARY_TYPE_ID = "binary type ID (@type_id)"; + + /** + * Adds the concrete specializations of the given message of all files in depth-first order. + */ + private static void addConcreteSpecializations(MessageDef def, List result, Set seen) { + for (MessageDef specialization : def.getSpecializations()) { + if (!seen.add(specialization)) { + continue; + } + if (!specialization.isAbstract()) { + result.add(specialization); + } + addConcreteSpecializations(specialization, result, seen); + } + } + + /** + * The identifiers of the given concrete message in polymorphic values of all generated formats, + * indexed by a description of the identifier and the annotation that sets it. + */ + private Map typeIds(MessageDef message, GeneratorPlugin plugin) { + DefinitionFile file = Util.definingFile(message); + Map options = file.getOptions(); + Map result = new java.util.LinkedHashMap<>(); + if (MessageGenerator.isJson(options) || generatesTypeScript(file)) { + result.put("type ID (@Name)", MsgBufJsonProtocol.typeId(message)); + } + if (MessageGenerator.isBinary(options)) { + Option typeId = message.getOptions().get("type_id"); + if (typeId instanceof NumberOption) { + result.put(BINARY_TYPE_ID, Integer.toString((int) ((NumberOption) typeId).getValue())); + } + } + plugin.addTypeIds(options, message, result); + return result; + } + + private String describe(Definition def) { + return "message '" + Util.protoName(def) + "' of '" + sourceDescription(Util.definingFile(def)) + "'"; + } + + /** + * Rejects clashing constants in the TypeKind enum generated for the given hierarchy + * root. + */ + private void validateTypeKinds(MessageDef root, List errors) { + DefinitionFile rootFile = Util.definingFile(root); + if (!isGenerated(root) || MessageGenerator.isTrue(rootFile.getOptions().get("NoTypeKind"), false)) { + return; + } + Map constants = new HashMap<>(); + for (MessageDef message : AbstractMessageGenerator.concreteSpecializations(root)) { + String constant = CodeConvention.typeKindConstant(message); + MessageDef clash = constants.putIfAbsent(constant, message); + if (clash != null) { + errors.add(sourceDescription(Util.definingFile(message)) + ": In the hierarchy of '" + Util.protoName(root) + + "', " + describe(clash) + " and " + describe(message) + " generate the same constant '" + constant + + "' in the enum '" + Util.toString(root) + "." + CodeConvention.TYPE_KIND_NAME + + "'. Rename one of the messages, or add 'option NoTypeKind;' to '" + sourceDescription(rootFile) + + "'" + (Util.definingFile(message) != rootFile || Util.definingFile(clash) != rootFile + ? " and all files extending its hierarchy" : "") + + "."); + } + } + } + + /** + * Rejects a message with the name of a nested definition of one of its generalizations. + */ + private void validateInheritedNames(MessageDef message, List errors) { + Set seen = new HashSet<>(); + seen.add(message); + for (MessageDef generalization = message.getExtendedDef(); generalization != null && seen.add(generalization); + generalization = generalization.getExtendedDef()) { + for (Definition member : generalization.getDefinitions()) { + if (member != message && member.getName().equals(message.getName())) { + errors.add(sourceDescription(Util.definingFile(message)) + ": Message '" + Util.protoName(message) + + "' extends message '" + Util.protoName(generalization) + "' of '" + + sourceDescription(Util.definingFile(generalization)) + "', which declares the nested " + + (member instanceof EnumDef ? "enum" : "message") + " '" + Util.protoName(member) + + "' with the same name. In the generated Java class of '" + Util.protoName(message) + + "', the name '" + message.getName() + "' would refer to the inherited nested type instead of the" + + " class itself. Rename one of them."); + return; + } + } + } + } + /** * Rejects references to definitions of other files that are generated without a serialization * format that the referencing code needs. @@ -802,6 +1024,7 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep if (resolved != null) { String canonical = resolved.getCanonicalPath(); if (_loadedFiles.contains(canonical)) { + addImport(file, _fileByPath.get(canonical)); continue; } _loadedFiles.add(canonical); @@ -809,6 +1032,8 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep try (InputStream in = new FileInputStream(resolved)) { imported = parse(in); } + _fileByPath.put(canonical, imported); + addImport(file, imported); _sourceNames.put(imported, resolved.getName()); _files.add(imported); _table.enter(imported); @@ -821,6 +1046,7 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep if (_importClassLoader != null) { String resourceKey = "classpath:" + importPath; if (_loadedFiles.contains(resourceKey)) { + addImport(file, _fileByPath.get(resourceKey)); continue; } InputStream classpathStream = _importClassLoader.getResourceAsStream(importPath); @@ -830,6 +1056,8 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep try (InputStream in = classpathStream) { imported = parse(in); } + _fileByPath.put(resourceKey, imported); + addImport(file, imported); _sourceNames.put(imported, new File(importPath).getName()); _files.add(imported); _table.enter(imported); @@ -844,10 +1072,17 @@ private void resolveImports(DefinitionFile file, File sourceFile) throws IOExcep } } + private void addImport(DefinitionFile file, DefinitionFile imported) { + if (imported != null && imported != file) { + _table.addImport(file, imported); + } + } + private void resolveImportsFromClasspath(DefinitionFile file) throws IOException, ParseException { for (String importPath : file.getImports()) { String resourceKey = "classpath:" + importPath; if (_loadedFiles.contains(resourceKey)) { + addImport(file, _fileByPath.get(resourceKey)); continue; } @@ -859,6 +1094,8 @@ private void resolveImportsFromClasspath(DefinitionFile file) throws IOException try (InputStream in = classpathStream) { imported = parse(in); } + _fileByPath.put(resourceKey, imported); + addImport(file, imported); _sourceNames.put(imported, new File(importPath).getName()); _files.add(imported); _table.enter(imported); diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java index a96a328d..a96b1fed 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/GeneratorPlugin.java @@ -100,6 +100,27 @@ default void addFieldFormats(Map options, Field field, Set + * The generator rejects two concrete specializations of an abstract message with the same + * identifier, since the readers of the abstract message cannot distinguish them. + *

+ * + * @param options + * The options of the file defining the message. + * @param def + * The concrete message. + * @param typeIds + * The identifiers to add to, indexed by a description of the identifier that names the + * annotation that sets it, e.g. "XML element name (@XmlName)". + */ + default void addTypeIds(Map options, MessageDef def, Map typeIds) { + // No additional identifiers by default. + } + /** * {@link GeneratorPlugin} that does not generate any output. */ @@ -142,6 +163,12 @@ public void addFieldFormats(Map options, Field field, Set options, MessageDef def, Map typeIds) { + self.addTypeIds(options, def, typeIds); + next.addTypeIds(options, def, typeIds); + } @Override public FileGenerator messageImplContents(Map options, MessageDef def) { diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java index 4465f381..d4578e31 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/MessageGenerator.java @@ -1890,8 +1890,12 @@ private void binaryWrite() { continue; } boolean nullable = Util.isNullable(field); + // The default value of a bytes field is null, which cannot be written. + boolean nullBytes = !nullable && Util.isSingleBytes(field); if (nullable) { line("if (" + hasName(field) + "()" + ") {"); + } else if (nullBytes) { + line("if (" + getterCall(field) + " != null) {"); } { line("out.name(" + binaryConstant(field) + ");"); @@ -1912,7 +1916,7 @@ private void binaryWrite() { binaryWriteValue(field.getType(), getterCall(field)); } } - if (nullable) { + if (nullable || nullBytes) { line("}"); } } @@ -1924,10 +1928,24 @@ private void binaryWrite() { private void binaryWriteValue(Type type, String x) { if (type instanceof PrimitiveType) { - if (((PrimitiveType) type).getKind() == Kind.JSON) { - line("de.haumacher.msgbuf.json.JsonUtil.toJsonValue(" + x + ").writeTo(out);"); - } else { - line("out.value(" + x + ");"); + switch (((PrimitiveType) type).getKind()) { + case JSON: + line("de.haumacher.msgbuf.json.JsonUtil.toJsonValue(" + x + ").writeTo(out);"); + break; + case SINT_32: + case SINT_64: + // Zig-zag encoding, as read by mkBinaryReadValue() and announced by mkBinaryType(). + line("out.valueSigned(" + x + ");"); + break; + case FIXED_32: + case SFIXED_32: + case FIXED_64: + case SFIXED_64: + // Fixed-length encoding, as read by mkBinaryReadValue() and announced by mkBinaryType(). + line("out.valueFixed(" + x + ");"); + break; + default: + line("out.value(" + x + ");"); } } else if (type instanceof CustomType) { line(x + ".writeTo(out);"); diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java index 0b74a64c..77534f74 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/NameTable.java @@ -3,10 +3,14 @@ */ package de.haumacher.msgbuf.generator; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; import de.haumacher.msgbuf.generator.ast.Constant; import de.haumacher.msgbuf.generator.ast.Definition; @@ -15,36 +19,59 @@ import de.haumacher.msgbuf.generator.ast.Field; import de.haumacher.msgbuf.generator.ast.MessageDef; import de.haumacher.msgbuf.generator.ast.QName; +import de.haumacher.msgbuf.generator.common.Util; /** - * TODO + * Index of all definitions of the files processed together, resolving type names. + * + *

+ * A name is resolved in the context of the message it is used in, see + * {@link #resolve(DefinitionFile, MessageDef, QName)}. + *

*/ public class NameTable implements Definition.Visitor { - + private final Map _packageByName = new HashMap<>(); - private final Map _definitionByName = new HashMap<>(); - + + /** + * The files imported by a file (its import declarations), in declaration order. + */ + private final Map> _imports = new HashMap<>(); + + /** + * Errors to report, formatted with a function describing the source of a file. + */ + private final List, String>> _errors = new ArrayList<>(); + public void enter(DefinitionFile file) { Package pkg = mkPackage(file.getPackage()); - + for (Definition def : file.getDefinitions()) { pkg.enter(file, def); def.visit(this, null); } } - + + /** + * Records that the given file imports the other file. + */ + public void addImport(DefinitionFile file, DefinitionFile imported) { + List list = _imports.computeIfAbsent(file, x -> new ArrayList<>()); + if (!list.contains(imported)) { + list.add(imported); + } + } + @Override public Void visit(EnumDef self, Void arg) { - enterDef(self); for (Constant part : self.getConstants()) { part.setOwner(self); } return null; } - + @Override public Void visit(MessageDef self, Void arg) { - enterDef(self); for (Field part : self.getFields()) { part.setOwner(self); } @@ -55,19 +82,8 @@ public Void visit(MessageDef self, Void arg) { return null; } - private void enterDef(Definition def) { - if (def.getOuter() == null) { - _definitionByName.put(def.getName(), def); - } - } - private Package mkPackage(QName qName) { - String name; - if (qName == null) { - name = ""; - } else { - name = CodeConvention.packageName(qName); - } + String name = packageName(qName); Package result = _packageByName.get(name); if (result == null) { result = new Package(name); @@ -76,13 +92,17 @@ private Package mkPackage(QName qName) { return result; } + private static String packageName(QName qName) { + return qName == null ? "" : CodeConvention.packageName(qName); + } + class Package { - + private final String _name; - + private final Map _definitionsByName = new HashMap<>(); - /** + /** * Creates a {@link Package}. */ public Package(String name) { @@ -92,33 +112,56 @@ public Package(String name) { public String getName() { return _name; } - - /** - * TODO - * @param file + + /** + * Enters the given top-level definition of the given file. */ public void enter(DefinitionFile file, Definition def) { def.setFile(file); - Definition clash = _definitionsByName.put(def.getName(), def); + Definition clash = _definitionsByName.putIfAbsent(def.getName(), def); if (clash != null) { - error("Duplicate definition '" + def.getName() + "' in package '" + getName() + "'."); + String qName = (getName().isEmpty() ? "" : getName() + ".") + def.getName(); + DefinitionFile clashFile = clash.getFile(); + _errors.add(source -> source.apply(file) + ": Duplicate definition of '" + qName + "'" + + (clashFile == file + ? ". Rename or remove one of the definitions." + : ", it is also defined in '" + source.apply(clashFile) + + "'. Rename one of the definitions, or do not pass both files to the generator.")); } } } - /** - * TODO + /** + * Reports the errors found so far (duplicate definitions and ambiguous names) and forgets them. + * + * @param source + * Function describing the source of a file in error messages. + * @return The error messages. + */ + public List drainErrors(Function source) { + List result = _errors.stream().map(e -> e.apply(source)).collect(Collectors.toList()); + _errors.clear(); + return result; + } + + /** + * Reports a problem that does not stop the generation. */ public void error(String message) { System.err.println(message); } /** - * TODO + * Resolves the given name used in the given message and reports an error, if the name cannot + * be resolved. + * + * @see #resolve(DefinitionFile, MessageDef, QName) */ public Definition lookup(MessageDef context, QName name) { - Definition result = resolve(context, name); - if (result == null) { + DefinitionFile file = context == null ? null : Util.definingFile(context); + int errorCount = _errors.size(); + Definition result = resolve(file, context, name, true); + if (result == null && _errors.size() == errorCount) { error("Name cannot be resolved" + (context == null ? "" : " in '" + context.getName() + "'") + ": " + CodeConvention.qTypeName(name)); } return result; @@ -132,13 +175,53 @@ public Definition lookup(MessageDef context, QName name) { * @param name * The name to resolve. * @return The resolved definition, or null if the name cannot be resolved. + * + * @see #resolve(DefinitionFile, MessageDef, QName) */ public Definition resolve(MessageDef context, QName name) { - String baseName = name.getNames().get(0); + return resolve(context == null ? null : Util.definingFile(context), context, name); + } - Definition base = lookupBase(context, baseName); + /** + * Resolves the given name in the given context without reporting an error. + * + *

+ * The first part of the name is resolved as follows: + *

+ *
    + *
  1. A nested definition of the context message or one of its outer messages.
  2. + *
  3. A top-level definition of the package of the given file (in any of the files processed + * together).
  4. + *
  5. A top-level definition of a file imported by the given file, if it is unique among these + * files. If none of them defines the name, the files imported by these files, and so on.
  6. + *
  7. For compatibility, a top-level definition of any other file processed together, if it is + * unique.
  8. + *
+ *

+ * The remaining parts are resolved as nested definitions. If this fails, the name is resolved as + * a package-qualified name. + *

+ * + * @param file + * The file in which the name is used, null if unknown. + * @param context + * The message in which the name is used, null for top-level usage. + * @param name + * The name to resolve. + * @return The resolved definition, or null if the name cannot be resolved (or is + * ambiguous). + */ + public Definition resolve(DefinitionFile file, MessageDef context, QName name) { + return resolve(file, context, name, false); + } - if (base != null) { + private Definition resolve(DefinitionFile file, MessageDef context, QName name, boolean report) { + String baseName = name.getNames().get(0); + + boolean[] fromImports = { false }; + List candidates = lookupBase(file, context, baseName, fromImports); + if (candidates.size() == 1) { + Definition base = candidates.get(0); // Try resolving remaining parts as inner definitions boolean resolved = true; for (int n = 1; n < name.getNames().size(); n++) { @@ -175,9 +258,29 @@ public Definition resolve(MessageDef context, QName name) { } } + if (report && candidates.size() > 1) { + String usage = context == null ? "" : " in '" + Util.protoName(context) + "'"; + String pkgName = file == null ? null : packageName(file.getPackage()); + _errors.add(source -> (file == null ? "" : source.apply(file) + ": ") + "The name '" + + CodeConvention.qTypeName(name) + "'" + usage + " is ambiguous, it could refer to " + + candidates.stream().map(c -> "'" + Util.protoName(c) + "' of '" + source.apply(c.getFile()) + "'") + .collect(Collectors.joining(" and ")) + + (pkgName == null ? "" + : fromImports[0] + ? ", which are defined in files imported by '" + source.apply(file) + "', and " + + packageDescription(pkgName) + " does not define this name" + : ". Neither " + packageDescription(pkgName) + " nor the files imported by '" + source.apply(file) + + "' define this name, and the candidates are defined in files that are not imported, but" + + " generated together") + + ". Use a qualified name, e.g. '" + Util.protoName(candidates.get(0)) + "'."); + } return null; } + private static String packageDescription(String pkgName) { + return pkgName.isEmpty() ? "the default package" : "package '" + pkgName + "'"; + } + private Definition lookupInner(Definition base, String nextName) { if (base instanceof MessageDef) { Optional match = ((MessageDef) base).getDefinitions().stream().filter(d -> nextName.equals(d.getName())).findFirst(); @@ -191,15 +294,70 @@ private Definition lookupInner(Definition base, String nextName) { } } - private Definition lookupBase(MessageDef context, String baseName) { + /** + * The candidates for the first part of a name. + * + * @param fromImports + * Output: whether the result consists of definitions of imported files. + * @return A single definition, if the name is resolved, more than one, if the name is + * ambiguous. + */ + private List lookupBase(DefinitionFile file, MessageDef context, String baseName, boolean[] fromImports) { while (context != null) { Definition inner = lookupInner(context, baseName); if (inner != null) { - return inner; + return List.of(inner); } context = context.getOuter(); } - - return _definitionByName.get(baseName); + + if (file != null) { + Package pkg = _packageByName.get(packageName(file.getPackage())); + Definition local = pkg == null ? null : pkg._definitionsByName.get(baseName); + if (local != null) { + return List.of(local); + } + + // Definitions of the files imported directly, then of the files imported by these, and so on. + java.util.Set seen = new java.util.HashSet<>(); + seen.add(file); + List level = List.of(file); + while (!level.isEmpty()) { + List next = new ArrayList<>(); + for (DefinitionFile current : level) { + for (DefinitionFile imported : _imports.getOrDefault(current, List.of())) { + if (seen.add(imported)) { + next.add(imported); + } + } + } + List found = new ArrayList<>(); + for (DefinitionFile imported : next) { + for (Definition def : imported.getDefinitions()) { + if (def.getName().equals(baseName) && !found.contains(def)) { + found.add(def); + } + } + } + if (!found.isEmpty()) { + fromImports[0] = true; + found.sort(Comparator.comparing(Util::protoName)); + return found; + } + level = next; + } + } + + // For compatibility, a definition of a file that is not imported can be referenced by its + // simple name, if it is unique among all files processed together. + List global = new ArrayList<>(); + for (Package pkg : _packageByName.values()) { + Definition def = pkg._definitionsByName.get(baseName); + if (def != null) { + global.add(def); + } + } + global.sort(Comparator.comparing(Util::protoName)); + return global; } } diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java index 2f0da893..bf302b36 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/common/Util.java @@ -78,6 +78,22 @@ public static String toString(Definition def) { } } + /** + * The name of the given definition qualified with its package and outer messages, as written in + * the .proto file. + */ + public static String protoName(Definition def) { + List names = new ArrayList<>(); + for (Definition current = def; current != null; current = current.getOuter()) { + names.add(0, current.getName()); + } + QName pkg = definingFile(def).getPackage(); + if (pkg != null) { + names.addAll(0, pkg.getNames()); + } + return String.join(".", names); + } + public static String toString(Part part) { return toString(part.getOwner()) + "#" + part.getName(); } @@ -95,6 +111,19 @@ public static boolean isNullable(Field field) { return getFlag(field, "Nullable") || (!field.isRepeated() && isNullable(field.getType())); } + /** + * Whether the given field is a single (not repeated) bytes field. + * + *

+ * The default value of such field is null, even if the field is not nullable. + *

+ */ + public static boolean isSingleBytes(Field field) { + Type type = field.getType(); + return !field.isRepeated() && type instanceof PrimitiveType + && ((PrimitiveType) type).getKind() == PrimitiveType.Kind.BYTES; + } + public static boolean isNullable(Type type) { if (type instanceof PrimitiveType) { return ((PrimitiveType) type).getKind() == PrimitiveType.Kind.JSON; diff --git a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java index 17d6451f..8d1890a7 100644 --- a/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java +++ b/de.haumacher.msgbuf.generator/src/main/java/de/haumacher/msgbuf/generator/plugins/XmlStreamingPlugin.java @@ -75,6 +75,13 @@ static boolean xmlSerialized(Field field) { return !field.isTransient() && !field.isDerived(); } + @Override + public void addTypeIds(Map options, MessageDef def, Map typeIds) { + if (!noXml(options)) { + typeIds.put("XML element name (@XmlName)", xmlTypeName(def, noXmlNames(options))); + } + } + @Override public void addInterfaces(Map options, MessageDef def, List generalizations) { if (noXml(options)) { @@ -180,7 +187,19 @@ protected void generate() { continue; } if (field.getType().kind() == Type.TypeKind.PRIMITIVE_TYPE || isEnum(field.getType())) { + // A missing value is omitted (a missing JSON value is written as JSON null). + boolean omitMissing = Util.isNullable(field) && !isJson(field); + // The default value of a bytes field is null, even if it is not nullable. + boolean omitNull = !Util.isNullable(field) && Util.isSingleBytes(field); + if (omitMissing) { + line("if (" + CodeConvention.hasName(field) + "()) {"); + } else if (omitNull) { + line("if (" + CodeConvention.getterName(field) + "() != null) {"); + } line("out.writeAttribute(" + xmlFieldNameConstant(field) + ", " + asString(field, CodeConvention.getterName(field) + "()") + ");"); + if (omitMissing || omitNull) { + line("}"); + } } } } @@ -513,15 +532,20 @@ protected void generate() { private void readPrimitiveXmlElement(Field field) { line("case " + xmlFieldNameConstant(field) + ": {"); { - line(setterName(field) + "(" + fromString(field, "in.getElementText()") + ");"); + if (field.isRepeated()) { + // The list parser evaluates its input twice. + line("String text = in.getElementText();"); + line(setterName(field) + "(" + fromString(field, "text") + ");"); + } else { + line(setterName(field) + "(" + fromString(field, "in.getElementText()") + ");"); + } line("break;"); } line("}"); } String xmlTypeNameRef(MessageDef def) { - // A nested specialization is not in scope by its simple name in the code of its generalization. - String implRef = def.getFile() == null ? qImplName(def) : implName(def); + String implRef = simpleNameInScopeOfGeneralizations(def) ? implName(def) : qImplName(def); return implRef + "." + xmlTypeNameConstant(def); } }; @@ -571,6 +595,10 @@ String readerMethod(MessageDef def) { } String xmlTypeName(MessageDef def) { + return xmlTypeName(def, _noXmlNames); + } + + private static String xmlTypeName(MessageDef def, boolean noXmlNames) { Optional
& 'quoted', comma é") + .setVBytes(SOME_BYTES) + .setVJson(json) + .setVColor(Color.GREEN); + + Values xml = checkValues(values); + assertEquals(UINT_ABOVE_2_31, xml.getVUint32()); + assertEquals(0xFFFFFFFF, xml.getVFixed32()); + assertTrue(Arrays.equals(SOME_BYTES, xml.getVBytes())); + assertEquals(Double.doubleToLongBits(-0.0), Double.doubleToLongBits(xml.getVDouble())); + + String written = toXml(values); + // Unsigned decimal, as expected by the reader. + assertTrue(written, written.contains("v-uint-32=\"3000000000\"")); + assertTrue(written, written.contains("v-fixed-32=\"4294967295\"")); + // Base64 + assertTrue(written, written.contains("v-bytes=\"AAH/f4Aq\"")); + } + + public void testValuesEmptyBytes() throws Exception { + Values xml = checkValues(Values.create().setVBytes(new byte[0])); + assertNotNull(xml.getVBytes()); + assertEquals(0, xml.getVBytes().length); + } + + public void testValuesSignedUint32Accepted() throws Exception { + // Signed decimal is still accepted for unsigned 32 bit values. + Values values = Values.readValues(reader("")); + assertEquals(-1, values.getVUint32()); + assertEquals(-2, values.getVFixed32()); + } + + public void testValuesElements() throws Exception { + Values values = Values.readValues(reader( + "4294967295AAH/f4AqRED")); + assertEquals(-1, values.getVUint32()); + assertTrue(Arrays.equals(SOME_BYTES, values.getVBytes())); + assertEquals(Color.RED, values.getVColor()); + } + + public void testListsEmpty() throws Exception { + Lists xml = checkLists(Lists.create()); + assertTrue(xml.getLInt32().isEmpty()); + assertTrue(xml.getLString().isEmpty()); + assertTrue(xml.getLBytes().isEmpty()); + } + + public void testListsEdge() throws Exception { + Lists lists = Lists.create() + .setLBool(Arrays.asList(true, false)) + .setLInt32(Arrays.asList(Integer.MIN_VALUE, -1, 0, Integer.MAX_VALUE)) + .setLSint32(Arrays.asList(-7, 7)) + .setLUint32(Arrays.asList(UINT_ABOVE_2_31, 0, -1)) + .setLFixed32(Arrays.asList(0xFFFFFFFF, 1)) + .setLSfixed32(Arrays.asList(-1)) + .setLInt64(Arrays.asList(Long.MIN_VALUE, Long.MAX_VALUE)) + .setLSint64(Arrays.asList(-3L)) + .setLUint64(Arrays.asList(-1L, 0L)) + .setLFixed64(Arrays.asList(Long.MAX_VALUE)) + .setLSfixed64(Arrays.asList(-1L, 5L)) + .setLFloat(Arrays.asList(-1.5f, 0.25f)) + .setLDouble(Arrays.asList(1e300, -0.0)) + .setLString(Arrays.asList("a", "", "d e")) + .setLBytes(Arrays.asList(SOME_BYTES, new byte[0], new byte[] { 7 })) + .setLColor(Arrays.asList(Color.GREEN, Color.RED)); + + Lists xml = checkLists(lists); + assertEquals(Arrays.asList(UINT_ABOVE_2_31, 0, -1), xml.getLUint32()); + assertEquals(3, xml.getLBytes().size()); + assertTrue(Arrays.equals(SOME_BYTES, xml.getLBytes().get(0))); + assertEquals(0, xml.getLBytes().get(1).length); + + String written = toXml(lists); + assertTrue(written, written.contains("l-uint-32=\"3000000000, 0, 4294967295\"")); + } + + public void testListsElements() throws Exception { + Lists lists = Lists.readLists(reader( + "1, 2,3AAH/f4Aq, Bw==")); + assertEquals(Arrays.asList(1, 2, 3), lists.getLInt32()); + assertEquals(Collections.emptyList(), lists.getLUint32()); + assertEquals(2, lists.getLBytes().size()); + assertTrue(Arrays.equals(new byte[] { 7 }, lists.getLBytes().get(1))); + } + + public void testNullablesUnset() throws Exception { + Nullables xml = checkNullables(Nullables.create()); + assertFalse(xml.hasNInt32()); + assertFalse(xml.hasNUint32()); + assertFalse(xml.hasNBytes()); + assertFalse(xml.hasNString()); + assertFalse(xml.hasNColor()); + assertFalse(xml.hasNJson()); + } + + public void testNullablesSet() throws Exception { + List json = new ArrayList<>(); + json.add("x"); + json.add(Collections.singletonMap("k", "v")); + + Nullables nullables = Nullables.create() + .setNBool(false) + .setNInt32(0) + .setNSint32(-1) + .setNUint32(UINT_ABOVE_2_31) + .setNFixed32(-1) + .setNSfixed32(Integer.MIN_VALUE) + .setNInt64(0L) + .setNSint64(-1L) + .setNUint64(-1L) + .setNFixed64(1L) + .setNSfixed64(Long.MIN_VALUE) + .setNFloat(0.0f) + .setNDouble(Double.MAX_VALUE) + .setNString("") + .setNBytes(new byte[0]) + .setNJson(json) + .setNColor(Color.RED) + .setNlInt32(new ArrayList<>()) + .setNlUint32(Arrays.asList(UINT_ABOVE_2_31)) + .setNlString(Arrays.asList("s")) + .setNlBytes(Arrays.asList(SOME_BYTES)); + + Nullables xml = checkNullables(nullables); + assertTrue(xml.hasNInt32()); + assertEquals(Integer.valueOf(UINT_ABOVE_2_31), xml.getNUint32()); + assertTrue(xml.hasNString()); + assertEquals("", xml.getNString()); + assertTrue(xml.hasNBytes()); + assertEquals(0, xml.getNBytes().length); + assertTrue(xml.hasNlInt32()); + assertTrue(xml.getNlInt32().isEmpty()); + assertTrue(Arrays.equals(SOME_BYTES, xml.getNlBytes().get(0))); + } + + /** + * Checks round-trips in all formats and returns the value read back from XML. + */ + private Values checkValues(Values values) throws Exception { + String expected = values.toString(); + assertEquals(expected, Values.readValues(new JsonReader(new StringR(expected))).toString()); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + values.writeTo(new OctetDataWriter(buffer)); + assertEquals(expected, Values.readValues(new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))).toString()); + + String xml = toXml(values); + Values result = Values.readValues(reader(xml)); + assertEquals(xml, expected, result.toString()); + assertEquals(xml, toXml(result)); + return result; + } + + private Lists checkLists(Lists lists) throws Exception { + String expected = lists.toString(); + assertEquals(expected, Lists.readLists(new JsonReader(new StringR(expected))).toString()); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + lists.writeTo(new OctetDataWriter(buffer)); + assertEquals(expected, Lists.readLists(new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))).toString()); + + String xml = toXml(lists); + Lists result = Lists.readLists(reader(xml)); + assertEquals(xml, expected, result.toString()); + assertEquals(xml, toXml(result)); + return result; + } + + private Nullables checkNullables(Nullables nullables) throws Exception { + String expected = nullables.toString(); + assertEquals(expected, Nullables.readNullables(new JsonReader(new StringR(expected))).toString()); + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + nullables.writeTo(new OctetDataWriter(buffer)); + assertEquals(expected, Nullables.readNullables(new OctetDataReader(new ByteArrayInputStream(buffer.toByteArray()))).toString()); + + String xml = toXml(nullables); + Nullables result = Nullables.readNullables(reader(xml)); + assertEquals(xml, expected, result.toString()); + assertEquals(xml, toXml(result)); + return result; + } + + private static String toXml(XmlSerializable value) throws XMLStreamException { + StringWriter buffer = new StringWriter(); + value.writeTo(XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(buffer)); + return buffer.toString(); + } + + private static XMLStreamReader reader(String xml) throws XMLStreamException, IOException { + return XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Color.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Color.java new file mode 100644 index 00000000..c944062f --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Color.java @@ -0,0 +1,64 @@ +package test.xmlprimitives.data; + +public enum Color implements de.haumacher.msgbuf.data.ProtocolEnum { + + RED("RED"), + + GREEN("GREEN"), + + ; + + private final String _protocolName; + + private Color(String protocolName) { + _protocolName = protocolName; + } + + /** + * The protocol name of a {@link Color} constant. + * + * @see #valueOfProtocol(String) + */ + @Override + public String protocolName() { + return _protocolName; + } + + /** Looks up a {@link Color} constant by it's protocol name. */ + public static Color valueOfProtocol(String protocolName) { + if (protocolName == null) { return null; } + switch (protocolName) { + case "RED": return RED; + case "GREEN": return GREEN; + } + return RED; + } + + /** Writes this instance to the given output. */ + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + out.value(protocolName()); + } + + /** Reads a new instance from the given reader. */ + public static Color readColor(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + return valueOfProtocol(in.nextString()); + } + + /** Writes this instance to the given binary output. */ + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + switch (this) { + case RED: out.value(1); break; + case GREEN: out.value(2); break; + default: out.value(0); + } + } + + /** Reads a new instance from the given binary reader. */ + public static Color readColor(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + switch (in.nextInt()) { + case 1: return RED; + case 2: return GREEN; + default: return RED; + } + } +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Lists.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Lists.java new file mode 100644 index 00000000..df08fc23 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Lists.java @@ -0,0 +1,413 @@ +package test.xmlprimitives.data; + +/** + * Every primitive type as repeated field. + */ +public interface Lists extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.xmlprimitives.data.Lists} instance. + */ + static test.xmlprimitives.data.Lists create() { + return new test.xmlprimitives.data.impl.Lists_Impl(); + } + + /** Identifier for the {@link test.xmlprimitives.data.Lists} type in JSON format. */ + String LISTS__TYPE = "Lists"; + + /** @see #isLBool() */ + String L_BOOL__PROP = "lBool"; + + /** @see #getLInt32() */ + String L_INT_32__PROP = "lInt32"; + + /** @see #getLSint32() */ + String L_SINT_32__PROP = "lSint32"; + + /** @see #getLUint32() */ + String L_UINT_32__PROP = "lUint32"; + + /** @see #getLFixed32() */ + String L_FIXED_32__PROP = "lFixed32"; + + /** @see #getLSfixed32() */ + String L_SFIXED_32__PROP = "lSfixed32"; + + /** @see #getLInt64() */ + String L_INT_64__PROP = "lInt64"; + + /** @see #getLSint64() */ + String L_SINT_64__PROP = "lSint64"; + + /** @see #getLUint64() */ + String L_UINT_64__PROP = "lUint64"; + + /** @see #getLFixed64() */ + String L_FIXED_64__PROP = "lFixed64"; + + /** @see #getLSfixed64() */ + String L_SFIXED_64__PROP = "lSfixed64"; + + /** @see #getLFloat() */ + String L_FLOAT__PROP = "lFloat"; + + /** @see #getLDouble() */ + String L_DOUBLE__PROP = "lDouble"; + + /** @see #getLString() */ + String L_STRING__PROP = "lString"; + + /** @see #getLBytes() */ + String L_BYTES__PROP = "lBytes"; + + /** @see #getLColor() */ + String L_COLOR__PROP = "lColor"; + + /** Identifier for the property {@link #isLBool()} in binary format. */ + static final int L_BOOL__ID = 1; + + /** Identifier for the property {@link #getLInt32()} in binary format. */ + static final int L_INT_32__ID = 2; + + /** Identifier for the property {@link #getLSint32()} in binary format. */ + static final int L_SINT_32__ID = 3; + + /** Identifier for the property {@link #getLUint32()} in binary format. */ + static final int L_UINT_32__ID = 4; + + /** Identifier for the property {@link #getLFixed32()} in binary format. */ + static final int L_FIXED_32__ID = 5; + + /** Identifier for the property {@link #getLSfixed32()} in binary format. */ + static final int L_SFIXED_32__ID = 6; + + /** Identifier for the property {@link #getLInt64()} in binary format. */ + static final int L_INT_64__ID = 7; + + /** Identifier for the property {@link #getLSint64()} in binary format. */ + static final int L_SINT_64__ID = 8; + + /** Identifier for the property {@link #getLUint64()} in binary format. */ + static final int L_UINT_64__ID = 9; + + /** Identifier for the property {@link #getLFixed64()} in binary format. */ + static final int L_FIXED_64__ID = 10; + + /** Identifier for the property {@link #getLSfixed64()} in binary format. */ + static final int L_SFIXED_64__ID = 11; + + /** Identifier for the property {@link #getLFloat()} in binary format. */ + static final int L_FLOAT__ID = 12; + + /** Identifier for the property {@link #getLDouble()} in binary format. */ + static final int L_DOUBLE__ID = 13; + + /** Identifier for the property {@link #getLString()} in binary format. */ + static final int L_STRING__ID = 14; + + /** Identifier for the property {@link #getLBytes()} in binary format. */ + static final int L_BYTES__ID = 15; + + /** Identifier for the property {@link #getLColor()} in binary format. */ + static final int L_COLOR__ID = 16; + + java.util.List isLBool(); + + /** + * @see #isLBool() + */ + test.xmlprimitives.data.Lists setLBool(java.util.List value); + + /** + * Adds a value to the {@link #isLBool()} list. + */ + test.xmlprimitives.data.Lists addLBool(boolean value); + + /** + * Removes a value from the {@link #isLBool()} list. + */ + void removeLBool(boolean value); + + java.util.List getLInt32(); + + /** + * @see #getLInt32() + */ + test.xmlprimitives.data.Lists setLInt32(java.util.List value); + + /** + * Adds a value to the {@link #getLInt32()} list. + */ + test.xmlprimitives.data.Lists addLInt32(int value); + + /** + * Removes a value from the {@link #getLInt32()} list. + */ + void removeLInt32(int value); + + java.util.List getLSint32(); + + /** + * @see #getLSint32() + */ + test.xmlprimitives.data.Lists setLSint32(java.util.List value); + + /** + * Adds a value to the {@link #getLSint32()} list. + */ + test.xmlprimitives.data.Lists addLSint32(int value); + + /** + * Removes a value from the {@link #getLSint32()} list. + */ + void removeLSint32(int value); + + java.util.List getLUint32(); + + /** + * @see #getLUint32() + */ + test.xmlprimitives.data.Lists setLUint32(java.util.List value); + + /** + * Adds a value to the {@link #getLUint32()} list. + */ + test.xmlprimitives.data.Lists addLUint32(int value); + + /** + * Removes a value from the {@link #getLUint32()} list. + */ + void removeLUint32(int value); + + java.util.List getLFixed32(); + + /** + * @see #getLFixed32() + */ + test.xmlprimitives.data.Lists setLFixed32(java.util.List value); + + /** + * Adds a value to the {@link #getLFixed32()} list. + */ + test.xmlprimitives.data.Lists addLFixed32(int value); + + /** + * Removes a value from the {@link #getLFixed32()} list. + */ + void removeLFixed32(int value); + + java.util.List getLSfixed32(); + + /** + * @see #getLSfixed32() + */ + test.xmlprimitives.data.Lists setLSfixed32(java.util.List value); + + /** + * Adds a value to the {@link #getLSfixed32()} list. + */ + test.xmlprimitives.data.Lists addLSfixed32(int value); + + /** + * Removes a value from the {@link #getLSfixed32()} list. + */ + void removeLSfixed32(int value); + + java.util.List getLInt64(); + + /** + * @see #getLInt64() + */ + test.xmlprimitives.data.Lists setLInt64(java.util.List value); + + /** + * Adds a value to the {@link #getLInt64()} list. + */ + test.xmlprimitives.data.Lists addLInt64(long value); + + /** + * Removes a value from the {@link #getLInt64()} list. + */ + void removeLInt64(long value); + + java.util.List getLSint64(); + + /** + * @see #getLSint64() + */ + test.xmlprimitives.data.Lists setLSint64(java.util.List value); + + /** + * Adds a value to the {@link #getLSint64()} list. + */ + test.xmlprimitives.data.Lists addLSint64(long value); + + /** + * Removes a value from the {@link #getLSint64()} list. + */ + void removeLSint64(long value); + + java.util.List getLUint64(); + + /** + * @see #getLUint64() + */ + test.xmlprimitives.data.Lists setLUint64(java.util.List value); + + /** + * Adds a value to the {@link #getLUint64()} list. + */ + test.xmlprimitives.data.Lists addLUint64(long value); + + /** + * Removes a value from the {@link #getLUint64()} list. + */ + void removeLUint64(long value); + + java.util.List getLFixed64(); + + /** + * @see #getLFixed64() + */ + test.xmlprimitives.data.Lists setLFixed64(java.util.List value); + + /** + * Adds a value to the {@link #getLFixed64()} list. + */ + test.xmlprimitives.data.Lists addLFixed64(long value); + + /** + * Removes a value from the {@link #getLFixed64()} list. + */ + void removeLFixed64(long value); + + java.util.List getLSfixed64(); + + /** + * @see #getLSfixed64() + */ + test.xmlprimitives.data.Lists setLSfixed64(java.util.List value); + + /** + * Adds a value to the {@link #getLSfixed64()} list. + */ + test.xmlprimitives.data.Lists addLSfixed64(long value); + + /** + * Removes a value from the {@link #getLSfixed64()} list. + */ + void removeLSfixed64(long value); + + java.util.List getLFloat(); + + /** + * @see #getLFloat() + */ + test.xmlprimitives.data.Lists setLFloat(java.util.List value); + + /** + * Adds a value to the {@link #getLFloat()} list. + */ + test.xmlprimitives.data.Lists addLFloat(float value); + + /** + * Removes a value from the {@link #getLFloat()} list. + */ + void removeLFloat(float value); + + java.util.List getLDouble(); + + /** + * @see #getLDouble() + */ + test.xmlprimitives.data.Lists setLDouble(java.util.List value); + + /** + * Adds a value to the {@link #getLDouble()} list. + */ + test.xmlprimitives.data.Lists addLDouble(double value); + + /** + * Removes a value from the {@link #getLDouble()} list. + */ + void removeLDouble(double value); + + java.util.List getLString(); + + /** + * @see #getLString() + */ + test.xmlprimitives.data.Lists setLString(java.util.List value); + + /** + * Adds a value to the {@link #getLString()} list. + */ + test.xmlprimitives.data.Lists addLString(String value); + + /** + * Removes a value from the {@link #getLString()} list. + */ + void removeLString(String value); + + java.util.List getLBytes(); + + /** + * @see #getLBytes() + */ + test.xmlprimitives.data.Lists setLBytes(java.util.List value); + + /** + * Adds a value to the {@link #getLBytes()} list. + */ + test.xmlprimitives.data.Lists addLByte(byte[] value); + + /** + * Removes a value from the {@link #getLBytes()} list. + */ + void removeLByte(byte[] value); + + java.util.List getLColor(); + + /** + * @see #getLColor() + */ + test.xmlprimitives.data.Lists setLColor(java.util.List value); + + /** + * Adds a value to the {@link #getLColor()} list. + */ + test.xmlprimitives.data.Lists addLColor(test.xmlprimitives.data.Color value); + + /** + * Removes a value from the {@link #getLColor()} list. + */ + void removeLColor(test.xmlprimitives.data.Color value); + + @Override + public test.xmlprimitives.data.Lists registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.xmlprimitives.data.Lists unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Lists readLists(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Lists_Impl result = new test.xmlprimitives.data.impl.Lists_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Lists readLists(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.xmlprimitives.data.Lists result = test.xmlprimitives.data.impl.Lists_Impl.readLists_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Lists} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Lists readLists(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.xmlprimitives.data.impl.Lists_Impl.readLists_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Nullables.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Nullables.java new file mode 100644 index 00000000..b9988329 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Nullables.java @@ -0,0 +1,463 @@ +package test.xmlprimitives.data; + +/** + * Every primitive type as nullable field. + */ +public interface Nullables extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.xmlprimitives.data.Nullables} instance. + */ + static test.xmlprimitives.data.Nullables create() { + return new test.xmlprimitives.data.impl.Nullables_Impl(); + } + + /** Identifier for the {@link test.xmlprimitives.data.Nullables} type in JSON format. */ + String NULLABLES__TYPE = "Nullables"; + + /** @see #getNBool() */ + String N_BOOL__PROP = "nBool"; + + /** @see #getNInt32() */ + String N_INT_32__PROP = "nInt32"; + + /** @see #getNSint32() */ + String N_SINT_32__PROP = "nSint32"; + + /** @see #getNUint32() */ + String N_UINT_32__PROP = "nUint32"; + + /** @see #getNFixed32() */ + String N_FIXED_32__PROP = "nFixed32"; + + /** @see #getNSfixed32() */ + String N_SFIXED_32__PROP = "nSfixed32"; + + /** @see #getNInt64() */ + String N_INT_64__PROP = "nInt64"; + + /** @see #getNSint64() */ + String N_SINT_64__PROP = "nSint64"; + + /** @see #getNUint64() */ + String N_UINT_64__PROP = "nUint64"; + + /** @see #getNFixed64() */ + String N_FIXED_64__PROP = "nFixed64"; + + /** @see #getNSfixed64() */ + String N_SFIXED_64__PROP = "nSfixed64"; + + /** @see #getNFloat() */ + String N_FLOAT__PROP = "nFloat"; + + /** @see #getNDouble() */ + String N_DOUBLE__PROP = "nDouble"; + + /** @see #getNString() */ + String N_STRING__PROP = "nString"; + + /** @see #getNBytes() */ + String N_BYTES__PROP = "nBytes"; + + /** @see #getNJson() */ + String N_JSON__PROP = "nJson"; + + /** @see #getNColor() */ + String N_COLOR__PROP = "nColor"; + + /** @see #getNlInt32() */ + String NL_INT_32__PROP = "nlInt32"; + + /** @see #getNlUint32() */ + String NL_UINT_32__PROP = "nlUint32"; + + /** @see #getNlString() */ + String NL_STRING__PROP = "nlString"; + + /** @see #getNlBytes() */ + String NL_BYTES__PROP = "nlBytes"; + + /** Identifier for the property {@link #getNBool()} in binary format. */ + static final int N_BOOL__ID = 1; + + /** Identifier for the property {@link #getNInt32()} in binary format. */ + static final int N_INT_32__ID = 2; + + /** Identifier for the property {@link #getNSint32()} in binary format. */ + static final int N_SINT_32__ID = 3; + + /** Identifier for the property {@link #getNUint32()} in binary format. */ + static final int N_UINT_32__ID = 4; + + /** Identifier for the property {@link #getNFixed32()} in binary format. */ + static final int N_FIXED_32__ID = 5; + + /** Identifier for the property {@link #getNSfixed32()} in binary format. */ + static final int N_SFIXED_32__ID = 6; + + /** Identifier for the property {@link #getNInt64()} in binary format. */ + static final int N_INT_64__ID = 7; + + /** Identifier for the property {@link #getNSint64()} in binary format. */ + static final int N_SINT_64__ID = 8; + + /** Identifier for the property {@link #getNUint64()} in binary format. */ + static final int N_UINT_64__ID = 9; + + /** Identifier for the property {@link #getNFixed64()} in binary format. */ + static final int N_FIXED_64__ID = 10; + + /** Identifier for the property {@link #getNSfixed64()} in binary format. */ + static final int N_SFIXED_64__ID = 11; + + /** Identifier for the property {@link #getNFloat()} in binary format. */ + static final int N_FLOAT__ID = 12; + + /** Identifier for the property {@link #getNDouble()} in binary format. */ + static final int N_DOUBLE__ID = 13; + + /** Identifier for the property {@link #getNString()} in binary format. */ + static final int N_STRING__ID = 14; + + /** Identifier for the property {@link #getNBytes()} in binary format. */ + static final int N_BYTES__ID = 15; + + /** Identifier for the property {@link #getNJson()} in binary format. */ + static final int N_JSON__ID = 16; + + /** Identifier for the property {@link #getNColor()} in binary format. */ + static final int N_COLOR__ID = 17; + + /** Identifier for the property {@link #getNlInt32()} in binary format. */ + static final int NL_INT_32__ID = 18; + + /** Identifier for the property {@link #getNlUint32()} in binary format. */ + static final int NL_UINT_32__ID = 19; + + /** Identifier for the property {@link #getNlString()} in binary format. */ + static final int NL_STRING__ID = 20; + + /** Identifier for the property {@link #getNlBytes()} in binary format. */ + static final int NL_BYTES__ID = 21; + + Boolean getNBool(); + + /** + * @see #getNBool() + */ + test.xmlprimitives.data.Nullables setNBool(Boolean value); + + /** + * Checks, whether {@link #getNBool()} has a value. + */ + boolean hasNBool(); + + Integer getNInt32(); + + /** + * @see #getNInt32() + */ + test.xmlprimitives.data.Nullables setNInt32(Integer value); + + /** + * Checks, whether {@link #getNInt32()} has a value. + */ + boolean hasNInt32(); + + Integer getNSint32(); + + /** + * @see #getNSint32() + */ + test.xmlprimitives.data.Nullables setNSint32(Integer value); + + /** + * Checks, whether {@link #getNSint32()} has a value. + */ + boolean hasNSint32(); + + Integer getNUint32(); + + /** + * @see #getNUint32() + */ + test.xmlprimitives.data.Nullables setNUint32(Integer value); + + /** + * Checks, whether {@link #getNUint32()} has a value. + */ + boolean hasNUint32(); + + Integer getNFixed32(); + + /** + * @see #getNFixed32() + */ + test.xmlprimitives.data.Nullables setNFixed32(Integer value); + + /** + * Checks, whether {@link #getNFixed32()} has a value. + */ + boolean hasNFixed32(); + + Integer getNSfixed32(); + + /** + * @see #getNSfixed32() + */ + test.xmlprimitives.data.Nullables setNSfixed32(Integer value); + + /** + * Checks, whether {@link #getNSfixed32()} has a value. + */ + boolean hasNSfixed32(); + + Long getNInt64(); + + /** + * @see #getNInt64() + */ + test.xmlprimitives.data.Nullables setNInt64(Long value); + + /** + * Checks, whether {@link #getNInt64()} has a value. + */ + boolean hasNInt64(); + + Long getNSint64(); + + /** + * @see #getNSint64() + */ + test.xmlprimitives.data.Nullables setNSint64(Long value); + + /** + * Checks, whether {@link #getNSint64()} has a value. + */ + boolean hasNSint64(); + + Long getNUint64(); + + /** + * @see #getNUint64() + */ + test.xmlprimitives.data.Nullables setNUint64(Long value); + + /** + * Checks, whether {@link #getNUint64()} has a value. + */ + boolean hasNUint64(); + + Long getNFixed64(); + + /** + * @see #getNFixed64() + */ + test.xmlprimitives.data.Nullables setNFixed64(Long value); + + /** + * Checks, whether {@link #getNFixed64()} has a value. + */ + boolean hasNFixed64(); + + Long getNSfixed64(); + + /** + * @see #getNSfixed64() + */ + test.xmlprimitives.data.Nullables setNSfixed64(Long value); + + /** + * Checks, whether {@link #getNSfixed64()} has a value. + */ + boolean hasNSfixed64(); + + Float getNFloat(); + + /** + * @see #getNFloat() + */ + test.xmlprimitives.data.Nullables setNFloat(Float value); + + /** + * Checks, whether {@link #getNFloat()} has a value. + */ + boolean hasNFloat(); + + Double getNDouble(); + + /** + * @see #getNDouble() + */ + test.xmlprimitives.data.Nullables setNDouble(Double value); + + /** + * Checks, whether {@link #getNDouble()} has a value. + */ + boolean hasNDouble(); + + String getNString(); + + /** + * @see #getNString() + */ + test.xmlprimitives.data.Nullables setNString(String value); + + /** + * Checks, whether {@link #getNString()} has a value. + */ + boolean hasNString(); + + byte[] getNBytes(); + + /** + * @see #getNBytes() + */ + test.xmlprimitives.data.Nullables setNBytes(byte[] value); + + /** + * Checks, whether {@link #getNBytes()} has a value. + */ + boolean hasNBytes(); + + Object getNJson(); + + /** + * @see #getNJson() + */ + test.xmlprimitives.data.Nullables setNJson(Object value); + + /** + * Checks, whether {@link #getNJson()} has a value. + */ + boolean hasNJson(); + + test.xmlprimitives.data.Color getNColor(); + + /** + * @see #getNColor() + */ + test.xmlprimitives.data.Nullables setNColor(test.xmlprimitives.data.Color value); + + /** + * Checks, whether {@link #getNColor()} has a value. + */ + boolean hasNColor(); + + java.util.List getNlInt32(); + + /** + * @see #getNlInt32() + */ + test.xmlprimitives.data.Nullables setNlInt32(java.util.List value); + + /** + * Adds a value to the {@link #getNlInt32()} list. + */ + test.xmlprimitives.data.Nullables addNlInt32(int value); + + /** + * Removes a value from the {@link #getNlInt32()} list. + */ + void removeNlInt32(int value); + + /** + * Checks, whether {@link #getNlInt32()} has a value. + */ + boolean hasNlInt32(); + + java.util.List getNlUint32(); + + /** + * @see #getNlUint32() + */ + test.xmlprimitives.data.Nullables setNlUint32(java.util.List value); + + /** + * Adds a value to the {@link #getNlUint32()} list. + */ + test.xmlprimitives.data.Nullables addNlUint32(int value); + + /** + * Removes a value from the {@link #getNlUint32()} list. + */ + void removeNlUint32(int value); + + /** + * Checks, whether {@link #getNlUint32()} has a value. + */ + boolean hasNlUint32(); + + java.util.List getNlString(); + + /** + * @see #getNlString() + */ + test.xmlprimitives.data.Nullables setNlString(java.util.List value); + + /** + * Adds a value to the {@link #getNlString()} list. + */ + test.xmlprimitives.data.Nullables addNlString(String value); + + /** + * Removes a value from the {@link #getNlString()} list. + */ + void removeNlString(String value); + + /** + * Checks, whether {@link #getNlString()} has a value. + */ + boolean hasNlString(); + + java.util.List getNlBytes(); + + /** + * @see #getNlBytes() + */ + test.xmlprimitives.data.Nullables setNlBytes(java.util.List value); + + /** + * Adds a value to the {@link #getNlBytes()} list. + */ + test.xmlprimitives.data.Nullables addNlByte(byte[] value); + + /** + * Removes a value from the {@link #getNlBytes()} list. + */ + void removeNlByte(byte[] value); + + /** + * Checks, whether {@link #getNlBytes()} has a value. + */ + boolean hasNlBytes(); + + @Override + public test.xmlprimitives.data.Nullables registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.xmlprimitives.data.Nullables unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Nullables readNullables(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Nullables_Impl result = new test.xmlprimitives.data.impl.Nullables_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Nullables readNullables(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.xmlprimitives.data.Nullables result = test.xmlprimitives.data.impl.Nullables_Impl.readNullables_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Nullables} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Nullables readNullables(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.xmlprimitives.data.impl.Nullables_Impl.readNullables_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Values.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Values.java new file mode 100644 index 00000000..a3364888 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/Values.java @@ -0,0 +1,271 @@ +package test.xmlprimitives.data; + +/** + * Every primitive type as singular field. + */ +public interface Values extends de.haumacher.msgbuf.data.DataObject, de.haumacher.msgbuf.binary.BinaryDataObject, de.haumacher.msgbuf.observer.Observable, de.haumacher.msgbuf.xml.XmlSerializable { + + /** + * Creates a {@link test.xmlprimitives.data.Values} instance. + */ + static test.xmlprimitives.data.Values create() { + return new test.xmlprimitives.data.impl.Values_Impl(); + } + + /** Identifier for the {@link test.xmlprimitives.data.Values} type in JSON format. */ + String VALUES__TYPE = "Values"; + + /** @see #isVBool() */ + String V_BOOL__PROP = "vBool"; + + /** @see #getVInt32() */ + String V_INT_32__PROP = "vInt32"; + + /** @see #getVSint32() */ + String V_SINT_32__PROP = "vSint32"; + + /** @see #getVUint32() */ + String V_UINT_32__PROP = "vUint32"; + + /** @see #getVFixed32() */ + String V_FIXED_32__PROP = "vFixed32"; + + /** @see #getVSfixed32() */ + String V_SFIXED_32__PROP = "vSfixed32"; + + /** @see #getVInt64() */ + String V_INT_64__PROP = "vInt64"; + + /** @see #getVSint64() */ + String V_SINT_64__PROP = "vSint64"; + + /** @see #getVUint64() */ + String V_UINT_64__PROP = "vUint64"; + + /** @see #getVFixed64() */ + String V_FIXED_64__PROP = "vFixed64"; + + /** @see #getVSfixed64() */ + String V_SFIXED_64__PROP = "vSfixed64"; + + /** @see #getVFloat() */ + String V_FLOAT__PROP = "vFloat"; + + /** @see #getVDouble() */ + String V_DOUBLE__PROP = "vDouble"; + + /** @see #getVString() */ + String V_STRING__PROP = "vString"; + + /** @see #getVBytes() */ + String V_BYTES__PROP = "vBytes"; + + /** @see #getVJson() */ + String V_JSON__PROP = "vJson"; + + /** @see #getVColor() */ + String V_COLOR__PROP = "vColor"; + + /** Identifier for the property {@link #isVBool()} in binary format. */ + static final int V_BOOL__ID = 1; + + /** Identifier for the property {@link #getVInt32()} in binary format. */ + static final int V_INT_32__ID = 2; + + /** Identifier for the property {@link #getVSint32()} in binary format. */ + static final int V_SINT_32__ID = 3; + + /** Identifier for the property {@link #getVUint32()} in binary format. */ + static final int V_UINT_32__ID = 4; + + /** Identifier for the property {@link #getVFixed32()} in binary format. */ + static final int V_FIXED_32__ID = 5; + + /** Identifier for the property {@link #getVSfixed32()} in binary format. */ + static final int V_SFIXED_32__ID = 6; + + /** Identifier for the property {@link #getVInt64()} in binary format. */ + static final int V_INT_64__ID = 7; + + /** Identifier for the property {@link #getVSint64()} in binary format. */ + static final int V_SINT_64__ID = 8; + + /** Identifier for the property {@link #getVUint64()} in binary format. */ + static final int V_UINT_64__ID = 9; + + /** Identifier for the property {@link #getVFixed64()} in binary format. */ + static final int V_FIXED_64__ID = 10; + + /** Identifier for the property {@link #getVSfixed64()} in binary format. */ + static final int V_SFIXED_64__ID = 11; + + /** Identifier for the property {@link #getVFloat()} in binary format. */ + static final int V_FLOAT__ID = 12; + + /** Identifier for the property {@link #getVDouble()} in binary format. */ + static final int V_DOUBLE__ID = 13; + + /** Identifier for the property {@link #getVString()} in binary format. */ + static final int V_STRING__ID = 14; + + /** Identifier for the property {@link #getVBytes()} in binary format. */ + static final int V_BYTES__ID = 15; + + /** Identifier for the property {@link #getVJson()} in binary format. */ + static final int V_JSON__ID = 16; + + /** Identifier for the property {@link #getVColor()} in binary format. */ + static final int V_COLOR__ID = 17; + + boolean isVBool(); + + /** + * @see #isVBool() + */ + test.xmlprimitives.data.Values setVBool(boolean value); + + int getVInt32(); + + /** + * @see #getVInt32() + */ + test.xmlprimitives.data.Values setVInt32(int value); + + int getVSint32(); + + /** + * @see #getVSint32() + */ + test.xmlprimitives.data.Values setVSint32(int value); + + int getVUint32(); + + /** + * @see #getVUint32() + */ + test.xmlprimitives.data.Values setVUint32(int value); + + int getVFixed32(); + + /** + * @see #getVFixed32() + */ + test.xmlprimitives.data.Values setVFixed32(int value); + + int getVSfixed32(); + + /** + * @see #getVSfixed32() + */ + test.xmlprimitives.data.Values setVSfixed32(int value); + + long getVInt64(); + + /** + * @see #getVInt64() + */ + test.xmlprimitives.data.Values setVInt64(long value); + + long getVSint64(); + + /** + * @see #getVSint64() + */ + test.xmlprimitives.data.Values setVSint64(long value); + + long getVUint64(); + + /** + * @see #getVUint64() + */ + test.xmlprimitives.data.Values setVUint64(long value); + + long getVFixed64(); + + /** + * @see #getVFixed64() + */ + test.xmlprimitives.data.Values setVFixed64(long value); + + long getVSfixed64(); + + /** + * @see #getVSfixed64() + */ + test.xmlprimitives.data.Values setVSfixed64(long value); + + float getVFloat(); + + /** + * @see #getVFloat() + */ + test.xmlprimitives.data.Values setVFloat(float value); + + double getVDouble(); + + /** + * @see #getVDouble() + */ + test.xmlprimitives.data.Values setVDouble(double value); + + String getVString(); + + /** + * @see #getVString() + */ + test.xmlprimitives.data.Values setVString(String value); + + byte[] getVBytes(); + + /** + * @see #getVBytes() + */ + test.xmlprimitives.data.Values setVBytes(byte[] value); + + Object getVJson(); + + /** + * @see #getVJson() + */ + test.xmlprimitives.data.Values setVJson(Object value); + + /** + * Checks, whether {@link #getVJson()} has a value. + */ + boolean hasVJson(); + + test.xmlprimitives.data.Color getVColor(); + + /** + * @see #getVColor() + */ + test.xmlprimitives.data.Values setVColor(test.xmlprimitives.data.Color value); + + @Override + public test.xmlprimitives.data.Values registerListener(de.haumacher.msgbuf.observer.Listener l); + + @Override + public test.xmlprimitives.data.Values unregisterListener(de.haumacher.msgbuf.observer.Listener l); + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Values readValues(de.haumacher.msgbuf.json.JsonReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Values_Impl result = new test.xmlprimitives.data.impl.Values_Impl(); + result.readContent(in); + return result; + } + + /** Reads a new instance from the given reader. */ + static test.xmlprimitives.data.Values readValues(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + in.beginObject(); + test.xmlprimitives.data.Values result = test.xmlprimitives.data.impl.Values_Impl.readValues_Content(in); + in.endObject(); + return result; + } + + /** Creates a new {@link Values} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Values readValues(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + in.nextTag(); + return test.xmlprimitives.data.impl.Values_Impl.readValues_XmlContent(in); + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Lists_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Lists_Impl.java new file mode 100644 index 00000000..d21ad88b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Lists_Impl.java @@ -0,0 +1,1800 @@ +package test.xmlprimitives.data.impl; + +/** + * Implementation of {@link test.xmlprimitives.data.Lists}. + */ +public class Lists_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.xmlprimitives.data.Lists { + + private final java.util.List _lBool = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Boolean element) { + _listener.beforeAdd(Lists_Impl.this, L_BOOL__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Boolean element) { + _listener.afterRemove(Lists_Impl.this, L_BOOL__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_BOOL__PROP); + } + }; + + private final java.util.List _lInt32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Lists_Impl.this, L_INT_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Lists_Impl.this, L_INT_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_INT_32__PROP); + } + }; + + private final java.util.List _lSint32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Lists_Impl.this, L_SINT_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Lists_Impl.this, L_SINT_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_SINT_32__PROP); + } + }; + + private final java.util.List _lUint32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Lists_Impl.this, L_UINT_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Lists_Impl.this, L_UINT_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_UINT_32__PROP); + } + }; + + private final java.util.List _lFixed32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Lists_Impl.this, L_FIXED_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Lists_Impl.this, L_FIXED_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_FIXED_32__PROP); + } + }; + + private final java.util.List _lSfixed32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Lists_Impl.this, L_SFIXED_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Lists_Impl.this, L_SFIXED_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_SFIXED_32__PROP); + } + }; + + private final java.util.List _lInt64 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Long element) { + _listener.beforeAdd(Lists_Impl.this, L_INT_64__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Long element) { + _listener.afterRemove(Lists_Impl.this, L_INT_64__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_INT_64__PROP); + } + }; + + private final java.util.List _lSint64 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Long element) { + _listener.beforeAdd(Lists_Impl.this, L_SINT_64__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Long element) { + _listener.afterRemove(Lists_Impl.this, L_SINT_64__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_SINT_64__PROP); + } + }; + + private final java.util.List _lUint64 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Long element) { + _listener.beforeAdd(Lists_Impl.this, L_UINT_64__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Long element) { + _listener.afterRemove(Lists_Impl.this, L_UINT_64__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_UINT_64__PROP); + } + }; + + private final java.util.List _lFixed64 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Long element) { + _listener.beforeAdd(Lists_Impl.this, L_FIXED_64__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Long element) { + _listener.afterRemove(Lists_Impl.this, L_FIXED_64__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_FIXED_64__PROP); + } + }; + + private final java.util.List _lSfixed64 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Long element) { + _listener.beforeAdd(Lists_Impl.this, L_SFIXED_64__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Long element) { + _listener.afterRemove(Lists_Impl.this, L_SFIXED_64__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_SFIXED_64__PROP); + } + }; + + private final java.util.List _lFloat = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Float element) { + _listener.beforeAdd(Lists_Impl.this, L_FLOAT__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Float element) { + _listener.afterRemove(Lists_Impl.this, L_FLOAT__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_FLOAT__PROP); + } + }; + + private final java.util.List _lDouble = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Double element) { + _listener.beforeAdd(Lists_Impl.this, L_DOUBLE__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Double element) { + _listener.afterRemove(Lists_Impl.this, L_DOUBLE__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_DOUBLE__PROP); + } + }; + + private final java.util.List _lString = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, String element) { + _listener.beforeAdd(Lists_Impl.this, L_STRING__PROP, index, element); + } + + @Override + protected void afterRemove(int index, String element) { + _listener.afterRemove(Lists_Impl.this, L_STRING__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_STRING__PROP); + } + }; + + private final java.util.List _lBytes = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, byte[] element) { + _listener.beforeAdd(Lists_Impl.this, L_BYTES__PROP, index, element); + } + + @Override + protected void afterRemove(int index, byte[] element) { + _listener.afterRemove(Lists_Impl.this, L_BYTES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_BYTES__PROP); + } + }; + + private final java.util.List _lColor = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, test.xmlprimitives.data.Color element) { + _listener.beforeAdd(Lists_Impl.this, L_COLOR__PROP, index, element); + } + + @Override + protected void afterRemove(int index, test.xmlprimitives.data.Color element) { + _listener.afterRemove(Lists_Impl.this, L_COLOR__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Lists_Impl.this, L_COLOR__PROP); + } + }; + + /** + * Creates a {@link Lists_Impl} instance. + * + * @see test.xmlprimitives.data.Lists#create() + */ + public Lists_Impl() { + super(); + } + + @Override + public final java.util.List isLBool() { + return _lBool; + } + + @Override + public test.xmlprimitives.data.Lists setLBool(java.util.List value) { + internalSetLBool(value); + return this; + } + + /** Internal setter for {@link #isLBool()} without chain call utility. */ + protected final void internalSetLBool(java.util.List value) { + _lBool.clear(); + _lBool.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLBool(boolean value) { + internalAddLBool(value); + return this; + } + + /** Implementation of {@link #addLBool(boolean)} without chain call utility. */ + protected final void internalAddLBool(boolean value) { + _lBool.add(value); + } + + @Override + public final void removeLBool(boolean value) { + _lBool.remove(value); + } + + @Override + public final java.util.List getLInt32() { + return _lInt32; + } + + @Override + public test.xmlprimitives.data.Lists setLInt32(java.util.List value) { + internalSetLInt32(value); + return this; + } + + /** Internal setter for {@link #getLInt32()} without chain call utility. */ + protected final void internalSetLInt32(java.util.List value) { + _lInt32.clear(); + _lInt32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLInt32(int value) { + internalAddLInt32(value); + return this; + } + + /** Implementation of {@link #addLInt32(int)} without chain call utility. */ + protected final void internalAddLInt32(int value) { + _lInt32.add(value); + } + + @Override + public final void removeLInt32(int value) { + _lInt32.remove(value); + } + + @Override + public final java.util.List getLSint32() { + return _lSint32; + } + + @Override + public test.xmlprimitives.data.Lists setLSint32(java.util.List value) { + internalSetLSint32(value); + return this; + } + + /** Internal setter for {@link #getLSint32()} without chain call utility. */ + protected final void internalSetLSint32(java.util.List value) { + _lSint32.clear(); + _lSint32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLSint32(int value) { + internalAddLSint32(value); + return this; + } + + /** Implementation of {@link #addLSint32(int)} without chain call utility. */ + protected final void internalAddLSint32(int value) { + _lSint32.add(value); + } + + @Override + public final void removeLSint32(int value) { + _lSint32.remove(value); + } + + @Override + public final java.util.List getLUint32() { + return _lUint32; + } + + @Override + public test.xmlprimitives.data.Lists setLUint32(java.util.List value) { + internalSetLUint32(value); + return this; + } + + /** Internal setter for {@link #getLUint32()} without chain call utility. */ + protected final void internalSetLUint32(java.util.List value) { + _lUint32.clear(); + _lUint32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLUint32(int value) { + internalAddLUint32(value); + return this; + } + + /** Implementation of {@link #addLUint32(int)} without chain call utility. */ + protected final void internalAddLUint32(int value) { + _lUint32.add(value); + } + + @Override + public final void removeLUint32(int value) { + _lUint32.remove(value); + } + + @Override + public final java.util.List getLFixed32() { + return _lFixed32; + } + + @Override + public test.xmlprimitives.data.Lists setLFixed32(java.util.List value) { + internalSetLFixed32(value); + return this; + } + + /** Internal setter for {@link #getLFixed32()} without chain call utility. */ + protected final void internalSetLFixed32(java.util.List value) { + _lFixed32.clear(); + _lFixed32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLFixed32(int value) { + internalAddLFixed32(value); + return this; + } + + /** Implementation of {@link #addLFixed32(int)} without chain call utility. */ + protected final void internalAddLFixed32(int value) { + _lFixed32.add(value); + } + + @Override + public final void removeLFixed32(int value) { + _lFixed32.remove(value); + } + + @Override + public final java.util.List getLSfixed32() { + return _lSfixed32; + } + + @Override + public test.xmlprimitives.data.Lists setLSfixed32(java.util.List value) { + internalSetLSfixed32(value); + return this; + } + + /** Internal setter for {@link #getLSfixed32()} without chain call utility. */ + protected final void internalSetLSfixed32(java.util.List value) { + _lSfixed32.clear(); + _lSfixed32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLSfixed32(int value) { + internalAddLSfixed32(value); + return this; + } + + /** Implementation of {@link #addLSfixed32(int)} without chain call utility. */ + protected final void internalAddLSfixed32(int value) { + _lSfixed32.add(value); + } + + @Override + public final void removeLSfixed32(int value) { + _lSfixed32.remove(value); + } + + @Override + public final java.util.List getLInt64() { + return _lInt64; + } + + @Override + public test.xmlprimitives.data.Lists setLInt64(java.util.List value) { + internalSetLInt64(value); + return this; + } + + /** Internal setter for {@link #getLInt64()} without chain call utility. */ + protected final void internalSetLInt64(java.util.List value) { + _lInt64.clear(); + _lInt64.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLInt64(long value) { + internalAddLInt64(value); + return this; + } + + /** Implementation of {@link #addLInt64(long)} without chain call utility. */ + protected final void internalAddLInt64(long value) { + _lInt64.add(value); + } + + @Override + public final void removeLInt64(long value) { + _lInt64.remove(value); + } + + @Override + public final java.util.List getLSint64() { + return _lSint64; + } + + @Override + public test.xmlprimitives.data.Lists setLSint64(java.util.List value) { + internalSetLSint64(value); + return this; + } + + /** Internal setter for {@link #getLSint64()} without chain call utility. */ + protected final void internalSetLSint64(java.util.List value) { + _lSint64.clear(); + _lSint64.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLSint64(long value) { + internalAddLSint64(value); + return this; + } + + /** Implementation of {@link #addLSint64(long)} without chain call utility. */ + protected final void internalAddLSint64(long value) { + _lSint64.add(value); + } + + @Override + public final void removeLSint64(long value) { + _lSint64.remove(value); + } + + @Override + public final java.util.List getLUint64() { + return _lUint64; + } + + @Override + public test.xmlprimitives.data.Lists setLUint64(java.util.List value) { + internalSetLUint64(value); + return this; + } + + /** Internal setter for {@link #getLUint64()} without chain call utility. */ + protected final void internalSetLUint64(java.util.List value) { + _lUint64.clear(); + _lUint64.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLUint64(long value) { + internalAddLUint64(value); + return this; + } + + /** Implementation of {@link #addLUint64(long)} without chain call utility. */ + protected final void internalAddLUint64(long value) { + _lUint64.add(value); + } + + @Override + public final void removeLUint64(long value) { + _lUint64.remove(value); + } + + @Override + public final java.util.List getLFixed64() { + return _lFixed64; + } + + @Override + public test.xmlprimitives.data.Lists setLFixed64(java.util.List value) { + internalSetLFixed64(value); + return this; + } + + /** Internal setter for {@link #getLFixed64()} without chain call utility. */ + protected final void internalSetLFixed64(java.util.List value) { + _lFixed64.clear(); + _lFixed64.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLFixed64(long value) { + internalAddLFixed64(value); + return this; + } + + /** Implementation of {@link #addLFixed64(long)} without chain call utility. */ + protected final void internalAddLFixed64(long value) { + _lFixed64.add(value); + } + + @Override + public final void removeLFixed64(long value) { + _lFixed64.remove(value); + } + + @Override + public final java.util.List getLSfixed64() { + return _lSfixed64; + } + + @Override + public test.xmlprimitives.data.Lists setLSfixed64(java.util.List value) { + internalSetLSfixed64(value); + return this; + } + + /** Internal setter for {@link #getLSfixed64()} without chain call utility. */ + protected final void internalSetLSfixed64(java.util.List value) { + _lSfixed64.clear(); + _lSfixed64.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLSfixed64(long value) { + internalAddLSfixed64(value); + return this; + } + + /** Implementation of {@link #addLSfixed64(long)} without chain call utility. */ + protected final void internalAddLSfixed64(long value) { + _lSfixed64.add(value); + } + + @Override + public final void removeLSfixed64(long value) { + _lSfixed64.remove(value); + } + + @Override + public final java.util.List getLFloat() { + return _lFloat; + } + + @Override + public test.xmlprimitives.data.Lists setLFloat(java.util.List value) { + internalSetLFloat(value); + return this; + } + + /** Internal setter for {@link #getLFloat()} without chain call utility. */ + protected final void internalSetLFloat(java.util.List value) { + _lFloat.clear(); + _lFloat.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLFloat(float value) { + internalAddLFloat(value); + return this; + } + + /** Implementation of {@link #addLFloat(float)} without chain call utility. */ + protected final void internalAddLFloat(float value) { + _lFloat.add(value); + } + + @Override + public final void removeLFloat(float value) { + _lFloat.remove(value); + } + + @Override + public final java.util.List getLDouble() { + return _lDouble; + } + + @Override + public test.xmlprimitives.data.Lists setLDouble(java.util.List value) { + internalSetLDouble(value); + return this; + } + + /** Internal setter for {@link #getLDouble()} without chain call utility. */ + protected final void internalSetLDouble(java.util.List value) { + _lDouble.clear(); + _lDouble.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLDouble(double value) { + internalAddLDouble(value); + return this; + } + + /** Implementation of {@link #addLDouble(double)} without chain call utility. */ + protected final void internalAddLDouble(double value) { + _lDouble.add(value); + } + + @Override + public final void removeLDouble(double value) { + _lDouble.remove(value); + } + + @Override + public final java.util.List getLString() { + return _lString; + } + + @Override + public test.xmlprimitives.data.Lists setLString(java.util.List value) { + internalSetLString(value); + return this; + } + + /** Internal setter for {@link #getLString()} without chain call utility. */ + protected final void internalSetLString(java.util.List value) { + _lString.clear(); + _lString.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLString(String value) { + internalAddLString(value); + return this; + } + + /** Implementation of {@link #addLString(String)} without chain call utility. */ + protected final void internalAddLString(String value) { + _lString.add(value); + } + + @Override + public final void removeLString(String value) { + _lString.remove(value); + } + + @Override + public final java.util.List getLBytes() { + return _lBytes; + } + + @Override + public test.xmlprimitives.data.Lists setLBytes(java.util.List value) { + internalSetLBytes(value); + return this; + } + + /** Internal setter for {@link #getLBytes()} without chain call utility. */ + protected final void internalSetLBytes(java.util.List value) { + _lBytes.clear(); + _lBytes.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLByte(byte[] value) { + internalAddLByte(value); + return this; + } + + /** Implementation of {@link #addLByte(byte[])} without chain call utility. */ + protected final void internalAddLByte(byte[] value) { + _lBytes.add(value); + } + + @Override + public final void removeLByte(byte[] value) { + _lBytes.remove(value); + } + + @Override + public final java.util.List getLColor() { + return _lColor; + } + + @Override + public test.xmlprimitives.data.Lists setLColor(java.util.List value) { + internalSetLColor(value); + return this; + } + + /** Internal setter for {@link #getLColor()} without chain call utility. */ + protected final void internalSetLColor(java.util.List value) { + if (value == null) throw new IllegalArgumentException("Property 'lColor' cannot be null."); + _lColor.clear(); + _lColor.addAll(value); + } + + @Override + public test.xmlprimitives.data.Lists addLColor(test.xmlprimitives.data.Color value) { + internalAddLColor(value); + return this; + } + + /** Implementation of {@link #addLColor(test.xmlprimitives.data.Color)} without chain call utility. */ + protected final void internalAddLColor(test.xmlprimitives.data.Color value) { + _lColor.add(value); + } + + @Override + public final void removeLColor(test.xmlprimitives.data.Color value) { + _lColor.remove(value); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.xmlprimitives.data.Lists registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.xmlprimitives.data.Lists unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return LISTS__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + L_BOOL__PROP, + L_INT_32__PROP, + L_SINT_32__PROP, + L_UINT_32__PROP, + L_FIXED_32__PROP, + L_SFIXED_32__PROP, + L_INT_64__PROP, + L_SINT_64__PROP, + L_UINT_64__PROP, + L_FIXED_64__PROP, + L_SFIXED_64__PROP, + L_FLOAT__PROP, + L_DOUBLE__PROP, + L_STRING__PROP, + L_BYTES__PROP, + L_COLOR__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case L_BOOL__PROP: return isLBool(); + case L_INT_32__PROP: return getLInt32(); + case L_SINT_32__PROP: return getLSint32(); + case L_UINT_32__PROP: return getLUint32(); + case L_FIXED_32__PROP: return getLFixed32(); + case L_SFIXED_32__PROP: return getLSfixed32(); + case L_INT_64__PROP: return getLInt64(); + case L_SINT_64__PROP: return getLSint64(); + case L_UINT_64__PROP: return getLUint64(); + case L_FIXED_64__PROP: return getLFixed64(); + case L_SFIXED_64__PROP: return getLSfixed64(); + case L_FLOAT__PROP: return getLFloat(); + case L_DOUBLE__PROP: return getLDouble(); + case L_STRING__PROP: return getLString(); + case L_BYTES__PROP: return getLBytes(); + case L_COLOR__PROP: return getLColor(); + default: return test.xmlprimitives.data.Lists.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case L_BOOL__PROP: internalSetLBool(de.haumacher.msgbuf.util.Conversions.asList(Boolean.class, value)); break; + case L_INT_32__PROP: internalSetLInt32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case L_SINT_32__PROP: internalSetLSint32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case L_UINT_32__PROP: internalSetLUint32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case L_FIXED_32__PROP: internalSetLFixed32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case L_SFIXED_32__PROP: internalSetLSfixed32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case L_INT_64__PROP: internalSetLInt64(de.haumacher.msgbuf.util.Conversions.asList(Long.class, value)); break; + case L_SINT_64__PROP: internalSetLSint64(de.haumacher.msgbuf.util.Conversions.asList(Long.class, value)); break; + case L_UINT_64__PROP: internalSetLUint64(de.haumacher.msgbuf.util.Conversions.asList(Long.class, value)); break; + case L_FIXED_64__PROP: internalSetLFixed64(de.haumacher.msgbuf.util.Conversions.asList(Long.class, value)); break; + case L_SFIXED_64__PROP: internalSetLSfixed64(de.haumacher.msgbuf.util.Conversions.asList(Long.class, value)); break; + case L_FLOAT__PROP: internalSetLFloat(de.haumacher.msgbuf.util.Conversions.asList(Float.class, value)); break; + case L_DOUBLE__PROP: internalSetLDouble(de.haumacher.msgbuf.util.Conversions.asList(Double.class, value)); break; + case L_STRING__PROP: internalSetLString(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; + case L_BYTES__PROP: internalSetLBytes(de.haumacher.msgbuf.util.Conversions.asList(byte[].class, value)); break; + case L_COLOR__PROP: internalSetLColor(de.haumacher.msgbuf.util.Conversions.asList(test.xmlprimitives.data.Color.class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(L_BOOL__PROP); + out.beginArray(); + for (boolean x : isLBool()) { + out.value(x); + } + out.endArray(); + out.name(L_INT_32__PROP); + out.beginArray(); + for (int x : getLInt32()) { + out.value(x); + } + out.endArray(); + out.name(L_SINT_32__PROP); + out.beginArray(); + for (int x : getLSint32()) { + out.value(x); + } + out.endArray(); + out.name(L_UINT_32__PROP); + out.beginArray(); + for (int x : getLUint32()) { + out.value(x); + } + out.endArray(); + out.name(L_FIXED_32__PROP); + out.beginArray(); + for (int x : getLFixed32()) { + out.value(x); + } + out.endArray(); + out.name(L_SFIXED_32__PROP); + out.beginArray(); + for (int x : getLSfixed32()) { + out.value(x); + } + out.endArray(); + out.name(L_INT_64__PROP); + out.beginArray(); + for (long x : getLInt64()) { + out.value(x); + } + out.endArray(); + out.name(L_SINT_64__PROP); + out.beginArray(); + for (long x : getLSint64()) { + out.value(x); + } + out.endArray(); + out.name(L_UINT_64__PROP); + out.beginArray(); + for (long x : getLUint64()) { + out.value(x); + } + out.endArray(); + out.name(L_FIXED_64__PROP); + out.beginArray(); + for (long x : getLFixed64()) { + out.value(x); + } + out.endArray(); + out.name(L_SFIXED_64__PROP); + out.beginArray(); + for (long x : getLSfixed64()) { + out.value(x); + } + out.endArray(); + out.name(L_FLOAT__PROP); + out.beginArray(); + for (float x : getLFloat()) { + out.value(x); + } + out.endArray(); + out.name(L_DOUBLE__PROP); + out.beginArray(); + for (double x : getLDouble()) { + out.value(x); + } + out.endArray(); + out.name(L_STRING__PROP); + out.beginArray(); + for (String x : getLString()) { + out.value(x); + } + out.endArray(); + out.name(L_BYTES__PROP); + out.beginArray(); + for (byte[] x : getLBytes()) { + de.haumacher.msgbuf.json.JsonUtil.writeBinaryOptional(out, x); + } + out.endArray(); + out.name(L_COLOR__PROP); + out.beginArray(); + for (test.xmlprimitives.data.Color x : getLColor()) { + x.writeTo(out); + } + out.endArray(); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case L_BOOL__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextBoolean()); + } + in.endArray(); + setLBool(newValue); + } + break; + case L_INT_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setLInt32(newValue); + } + break; + case L_SINT_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setLSint32(newValue); + } + break; + case L_UINT_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setLUint32(newValue); + } + break; + case L_FIXED_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setLFixed32(newValue); + } + break; + case L_SFIXED_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setLSfixed32(newValue); + } + break; + case L_INT_64__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextLong()); + } + in.endArray(); + setLInt64(newValue); + } + break; + case L_SINT_64__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextLong()); + } + in.endArray(); + setLSint64(newValue); + } + break; + case L_UINT_64__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextLong()); + } + in.endArray(); + setLUint64(newValue); + } + break; + case L_FIXED_64__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextLong()); + } + in.endArray(); + setLFixed64(newValue); + } + break; + case L_SFIXED_64__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextLong()); + } + in.endArray(); + setLSfixed64(newValue); + } + break; + case L_FLOAT__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add((float) in.nextDouble()); + } + in.endArray(); + setLFloat(newValue); + } + break; + case L_DOUBLE__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextDouble()); + } + in.endArray(); + setLDouble(newValue); + } + break; + case L_STRING__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); + } + in.endArray(); + setLString(newValue); + } + break; + case L_BYTES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextBinaryOptional(in)); + } + in.endArray(); + setLBytes(newValue); + } + break; + case L_COLOR__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(test.xmlprimitives.data.Color.readColor(in)); + } + in.endArray(); + setLColor(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(L_BOOL__ID); + { + java.util.List values = isLBool(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (boolean x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_INT_32__ID); + { + java.util.List values = getLInt32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (int x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_SINT_32__ID); + { + java.util.List values = getLSint32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.SINT, values.size()); + for (int x : values) { + out.valueSigned(x); + } + out.endArray(); + } + out.name(L_UINT_32__ID); + { + java.util.List values = getLUint32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (int x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_FIXED_32__ID); + { + java.util.List values = getLFixed32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.FINT, values.size()); + for (int x : values) { + out.valueFixed(x); + } + out.endArray(); + } + out.name(L_SFIXED_32__ID); + { + java.util.List values = getLSfixed32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.FINT, values.size()); + for (int x : values) { + out.valueFixed(x); + } + out.endArray(); + } + out.name(L_INT_64__ID); + { + java.util.List values = getLInt64(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.LONG, values.size()); + for (long x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_SINT_64__ID); + { + java.util.List values = getLSint64(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.SLONG, values.size()); + for (long x : values) { + out.valueSigned(x); + } + out.endArray(); + } + out.name(L_UINT_64__ID); + { + java.util.List values = getLUint64(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.LONG, values.size()); + for (long x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_FIXED_64__ID); + { + java.util.List values = getLFixed64(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.FLONG, values.size()); + for (long x : values) { + out.valueFixed(x); + } + out.endArray(); + } + out.name(L_SFIXED_64__ID); + { + java.util.List values = getLSfixed64(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.FLONG, values.size()); + for (long x : values) { + out.valueFixed(x); + } + out.endArray(); + } + out.name(L_FLOAT__ID); + { + java.util.List values = getLFloat(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.FLOAT, values.size()); + for (float x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_DOUBLE__ID); + { + java.util.List values = getLDouble(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.DOUBLE, values.size()); + for (double x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_STRING__ID); + { + java.util.List values = getLString(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.STRING, values.size()); + for (String x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_BYTES__ID); + { + java.util.List values = getLBytes(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.BINARY, values.size()); + for (byte[] x : values) { + out.value(x); + } + out.endArray(); + } + out.name(L_COLOR__ID); + { + java.util.List values = getLColor(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (test.xmlprimitives.data.Color x : values) { + x.writeTo(out); + } + out.endArray(); + } + } + + /** Helper for creating an object of type {@link test.xmlprimitives.data.Lists} from a polymorphic composition. */ + public static test.xmlprimitives.data.Lists readLists_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Lists_Impl result = new Lists_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case L_BOOL__ID: { + in.beginArray(); + while (in.hasNext()) { + addLBool(in.nextBoolean()); + } + in.endArray(); + } + break; + case L_INT_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addLInt32(in.nextInt()); + } + in.endArray(); + } + break; + case L_SINT_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addLSint32(in.nextIntSigned()); + } + in.endArray(); + } + break; + case L_UINT_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addLUint32(in.nextInt()); + } + in.endArray(); + } + break; + case L_FIXED_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addLFixed32(in.nextIntFixed()); + } + in.endArray(); + } + break; + case L_SFIXED_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addLSfixed32(in.nextIntFixed()); + } + in.endArray(); + } + break; + case L_INT_64__ID: { + in.beginArray(); + while (in.hasNext()) { + addLInt64(in.nextLong()); + } + in.endArray(); + } + break; + case L_SINT_64__ID: { + in.beginArray(); + while (in.hasNext()) { + addLSint64(in.nextLongSigned()); + } + in.endArray(); + } + break; + case L_UINT_64__ID: { + in.beginArray(); + while (in.hasNext()) { + addLUint64(in.nextLong()); + } + in.endArray(); + } + break; + case L_FIXED_64__ID: { + in.beginArray(); + while (in.hasNext()) { + addLFixed64(in.nextLongFixed()); + } + in.endArray(); + } + break; + case L_SFIXED_64__ID: { + in.beginArray(); + while (in.hasNext()) { + addLSfixed64(in.nextLongFixed()); + } + in.endArray(); + } + break; + case L_FLOAT__ID: { + in.beginArray(); + while (in.hasNext()) { + addLFloat(in.nextFloat()); + } + in.endArray(); + } + break; + case L_DOUBLE__ID: { + in.beginArray(); + while (in.hasNext()) { + addLDouble(in.nextDouble()); + } + in.endArray(); + } + break; + case L_STRING__ID: { + in.beginArray(); + while (in.hasNext()) { + addLString(in.nextString()); + } + in.endArray(); + } + break; + case L_BYTES__ID: { + in.beginArray(); + while (in.hasNext()) { + addLByte(in.nextBinary()); + } + in.endArray(); + } + break; + case L_COLOR__ID: { + in.beginArray(); + while (in.hasNext()) { + addLColor(test.xmlprimitives.data.Color.readColor(in)); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.xmlprimitives.data.Lists} type. */ + public static final String LISTS__XML_ELEMENT = "lists"; + + /** XML attribute or element name of a {@link #isLBool} property. */ + private static final String L_BOOL__XML_ATTR = "l-bool"; + + /** XML attribute or element name of a {@link #getLInt32} property. */ + private static final String L_INT_32__XML_ATTR = "l-int-32"; + + /** XML attribute or element name of a {@link #getLSint32} property. */ + private static final String L_SINT_32__XML_ATTR = "l-sint-32"; + + /** XML attribute or element name of a {@link #getLUint32} property. */ + private static final String L_UINT_32__XML_ATTR = "l-uint-32"; + + /** XML attribute or element name of a {@link #getLFixed32} property. */ + private static final String L_FIXED_32__XML_ATTR = "l-fixed-32"; + + /** XML attribute or element name of a {@link #getLSfixed32} property. */ + private static final String L_SFIXED_32__XML_ATTR = "l-sfixed-32"; + + /** XML attribute or element name of a {@link #getLInt64} property. */ + private static final String L_INT_64__XML_ATTR = "l-int-64"; + + /** XML attribute or element name of a {@link #getLSint64} property. */ + private static final String L_SINT_64__XML_ATTR = "l-sint-64"; + + /** XML attribute or element name of a {@link #getLUint64} property. */ + private static final String L_UINT_64__XML_ATTR = "l-uint-64"; + + /** XML attribute or element name of a {@link #getLFixed64} property. */ + private static final String L_FIXED_64__XML_ATTR = "l-fixed-64"; + + /** XML attribute or element name of a {@link #getLSfixed64} property. */ + private static final String L_SFIXED_64__XML_ATTR = "l-sfixed-64"; + + /** XML attribute or element name of a {@link #getLFloat} property. */ + private static final String L_FLOAT__XML_ATTR = "l-float"; + + /** XML attribute or element name of a {@link #getLDouble} property. */ + private static final String L_DOUBLE__XML_ATTR = "l-double"; + + /** XML attribute or element name of a {@link #getLString} property. */ + private static final String L_STRING__XML_ATTR = "l-string"; + + /** XML attribute or element name of a {@link #getLBytes} property. */ + private static final String L_BYTES__XML_ATTR = "l-bytes"; + + /** XML attribute or element name of a {@link #getLColor} property. */ + private static final String L_COLOR__XML_ATTR = "l-color"; + + @Override + public String getXmlTagName() { + return LISTS__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(L_BOOL__XML_ATTR, isLBool().stream().map(x -> Boolean.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_INT_32__XML_ATTR, getLInt32().stream().map(x -> Integer.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_SINT_32__XML_ATTR, getLSint32().stream().map(x -> Integer.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_UINT_32__XML_ATTR, getLUint32().stream().map(x -> Long.toString(Integer.toUnsignedLong(x))).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_FIXED_32__XML_ATTR, getLFixed32().stream().map(x -> Long.toString(Integer.toUnsignedLong(x))).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_SFIXED_32__XML_ATTR, getLSfixed32().stream().map(x -> Integer.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_INT_64__XML_ATTR, getLInt64().stream().map(x -> Long.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_SINT_64__XML_ATTR, getLSint64().stream().map(x -> Long.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_UINT_64__XML_ATTR, getLUint64().stream().map(x -> Long.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_FIXED_64__XML_ATTR, getLFixed64().stream().map(x -> Long.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_SFIXED_64__XML_ATTR, getLSfixed64().stream().map(x -> Long.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_FLOAT__XML_ATTR, getLFloat().stream().map(x -> Float.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_DOUBLE__XML_ATTR, getLDouble().stream().map(x -> Double.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_STRING__XML_ATTR, getLString().stream().map(x -> x).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_BYTES__XML_ATTR, getLBytes().stream().map(x -> java.util.Base64.getEncoder().encodeToString(x)).collect(java.util.stream.Collectors.joining(", "))); + out.writeAttribute(L_COLOR__XML_ATTR, getLColor().stream().map(x -> x.protocolName()).collect(java.util.stream.Collectors.joining(", "))); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.xmlprimitives.data.Lists} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Lists_Impl readLists_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Lists_Impl result = new Lists_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case L_BOOL__XML_ATTR: { + setLBool(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Boolean.parseBoolean(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_INT_32__XML_ATTR: { + setLInt32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SINT_32__XML_ATTR: { + setLSint32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_UINT_32__XML_ATTR: { + setLUint32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FIXED_32__XML_ATTR: { + setLFixed32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SFIXED_32__XML_ATTR: { + setLSfixed32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_INT_64__XML_ATTR: { + setLInt64(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SINT_64__XML_ATTR: { + setLSint64(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_UINT_64__XML_ATTR: { + setLUint64(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FIXED_64__XML_ATTR: { + setLFixed64(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SFIXED_64__XML_ATTR: { + setLSfixed64(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FLOAT__XML_ATTR: { + setLFloat(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Float.parseFloat(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_DOUBLE__XML_ATTR: { + setLDouble(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Double.parseDouble(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_STRING__XML_ATTR: { + setLString(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + case L_BYTES__XML_ATTR: { + setLBytes(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> java.util.Base64.getDecoder().decode(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_COLOR__XML_ATTR: { + setLColor(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> test.xmlprimitives.data.Color.valueOfProtocol(x)).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case L_BOOL__XML_ATTR: { + String text = in.getElementText(); + setLBool(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Boolean.parseBoolean(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_INT_32__XML_ATTR: { + String text = in.getElementText(); + setLInt32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SINT_32__XML_ATTR: { + String text = in.getElementText(); + setLSint32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_UINT_32__XML_ATTR: { + String text = in.getElementText(); + setLUint32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FIXED_32__XML_ATTR: { + String text = in.getElementText(); + setLFixed32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SFIXED_32__XML_ATTR: { + String text = in.getElementText(); + setLSfixed32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_INT_64__XML_ATTR: { + String text = in.getElementText(); + setLInt64(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SINT_64__XML_ATTR: { + String text = in.getElementText(); + setLSint64(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_UINT_64__XML_ATTR: { + String text = in.getElementText(); + setLUint64(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FIXED_64__XML_ATTR: { + String text = in.getElementText(); + setLFixed64(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_SFIXED_64__XML_ATTR: { + String text = in.getElementText(); + setLSfixed64(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_FLOAT__XML_ATTR: { + String text = in.getElementText(); + setLFloat(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Float.parseFloat(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_DOUBLE__XML_ATTR: { + String text = in.getElementText(); + setLDouble(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Double.parseDouble(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_STRING__XML_ATTR: { + String text = in.getElementText(); + setLString(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + case L_BYTES__XML_ATTR: { + String text = in.getElementText(); + setLBytes(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> java.util.Base64.getDecoder().decode(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case L_COLOR__XML_ATTR: { + String text = in.getElementText(); + setLColor(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> test.xmlprimitives.data.Color.valueOfProtocol(x)).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Nullables_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Nullables_Impl.java new file mode 100644 index 00000000..271534b5 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Nullables_Impl.java @@ -0,0 +1,1549 @@ +package test.xmlprimitives.data.impl; + +/** + * Implementation of {@link test.xmlprimitives.data.Nullables}. + */ +public class Nullables_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.xmlprimitives.data.Nullables { + + private Boolean _nBool = null; + + private Integer _nInt32 = null; + + private Integer _nSint32 = null; + + private Integer _nUint32 = null; + + private Integer _nFixed32 = null; + + private Integer _nSfixed32 = null; + + private Long _nInt64 = null; + + private Long _nSint64 = null; + + private Long _nUint64 = null; + + private Long _nFixed64 = null; + + private Long _nSfixed64 = null; + + private Float _nFloat = null; + + private Double _nDouble = null; + + private String _nString = null; + + private byte[] _nBytes = null; + + private Object _nJson = null; + + private test.xmlprimitives.data.Color _nColor = null; + + private java.util.List _nlInt32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Nullables_Impl.this, NL_INT_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Nullables_Impl.this, NL_INT_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Nullables_Impl.this, NL_INT_32__PROP); + } + }; + + private java.util.List _nlUint32 = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, Integer element) { + _listener.beforeAdd(Nullables_Impl.this, NL_UINT_32__PROP, index, element); + } + + @Override + protected void afterRemove(int index, Integer element) { + _listener.afterRemove(Nullables_Impl.this, NL_UINT_32__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Nullables_Impl.this, NL_UINT_32__PROP); + } + }; + + private java.util.List _nlString = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, String element) { + _listener.beforeAdd(Nullables_Impl.this, NL_STRING__PROP, index, element); + } + + @Override + protected void afterRemove(int index, String element) { + _listener.afterRemove(Nullables_Impl.this, NL_STRING__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Nullables_Impl.this, NL_STRING__PROP); + } + }; + + private java.util.List _nlBytes = new de.haumacher.msgbuf.util.ReferenceList() { + @Override + protected void beforeAdd(int index, byte[] element) { + _listener.beforeAdd(Nullables_Impl.this, NL_BYTES__PROP, index, element); + } + + @Override + protected void afterRemove(int index, byte[] element) { + _listener.afterRemove(Nullables_Impl.this, NL_BYTES__PROP, index, element); + } + + @Override + protected void afterChanged() { + _listener.afterChanged(Nullables_Impl.this, NL_BYTES__PROP); + } + }; + + /** + * Creates a {@link Nullables_Impl} instance. + * + * @see test.xmlprimitives.data.Nullables#create() + */ + public Nullables_Impl() { + super(); + } + + @Override + public final Boolean getNBool() { + return _nBool; + } + + @Override + public test.xmlprimitives.data.Nullables setNBool(Boolean value) { + internalSetNBool(value); + return this; + } + + /** Internal setter for {@link #getNBool()} without chain call utility. */ + protected final void internalSetNBool(Boolean value) { + _listener.beforeSet(this, N_BOOL__PROP, value); + _nBool = value; + _listener.afterChanged(this, N_BOOL__PROP); + } + + @Override + public final boolean hasNBool() { + return _nBool != null; + } + + @Override + public final Integer getNInt32() { + return _nInt32; + } + + @Override + public test.xmlprimitives.data.Nullables setNInt32(Integer value) { + internalSetNInt32(value); + return this; + } + + /** Internal setter for {@link #getNInt32()} without chain call utility. */ + protected final void internalSetNInt32(Integer value) { + _listener.beforeSet(this, N_INT_32__PROP, value); + _nInt32 = value; + _listener.afterChanged(this, N_INT_32__PROP); + } + + @Override + public final boolean hasNInt32() { + return _nInt32 != null; + } + + @Override + public final Integer getNSint32() { + return _nSint32; + } + + @Override + public test.xmlprimitives.data.Nullables setNSint32(Integer value) { + internalSetNSint32(value); + return this; + } + + /** Internal setter for {@link #getNSint32()} without chain call utility. */ + protected final void internalSetNSint32(Integer value) { + _listener.beforeSet(this, N_SINT_32__PROP, value); + _nSint32 = value; + _listener.afterChanged(this, N_SINT_32__PROP); + } + + @Override + public final boolean hasNSint32() { + return _nSint32 != null; + } + + @Override + public final Integer getNUint32() { + return _nUint32; + } + + @Override + public test.xmlprimitives.data.Nullables setNUint32(Integer value) { + internalSetNUint32(value); + return this; + } + + /** Internal setter for {@link #getNUint32()} without chain call utility. */ + protected final void internalSetNUint32(Integer value) { + _listener.beforeSet(this, N_UINT_32__PROP, value); + _nUint32 = value; + _listener.afterChanged(this, N_UINT_32__PROP); + } + + @Override + public final boolean hasNUint32() { + return _nUint32 != null; + } + + @Override + public final Integer getNFixed32() { + return _nFixed32; + } + + @Override + public test.xmlprimitives.data.Nullables setNFixed32(Integer value) { + internalSetNFixed32(value); + return this; + } + + /** Internal setter for {@link #getNFixed32()} without chain call utility. */ + protected final void internalSetNFixed32(Integer value) { + _listener.beforeSet(this, N_FIXED_32__PROP, value); + _nFixed32 = value; + _listener.afterChanged(this, N_FIXED_32__PROP); + } + + @Override + public final boolean hasNFixed32() { + return _nFixed32 != null; + } + + @Override + public final Integer getNSfixed32() { + return _nSfixed32; + } + + @Override + public test.xmlprimitives.data.Nullables setNSfixed32(Integer value) { + internalSetNSfixed32(value); + return this; + } + + /** Internal setter for {@link #getNSfixed32()} without chain call utility. */ + protected final void internalSetNSfixed32(Integer value) { + _listener.beforeSet(this, N_SFIXED_32__PROP, value); + _nSfixed32 = value; + _listener.afterChanged(this, N_SFIXED_32__PROP); + } + + @Override + public final boolean hasNSfixed32() { + return _nSfixed32 != null; + } + + @Override + public final Long getNInt64() { + return _nInt64; + } + + @Override + public test.xmlprimitives.data.Nullables setNInt64(Long value) { + internalSetNInt64(value); + return this; + } + + /** Internal setter for {@link #getNInt64()} without chain call utility. */ + protected final void internalSetNInt64(Long value) { + _listener.beforeSet(this, N_INT_64__PROP, value); + _nInt64 = value; + _listener.afterChanged(this, N_INT_64__PROP); + } + + @Override + public final boolean hasNInt64() { + return _nInt64 != null; + } + + @Override + public final Long getNSint64() { + return _nSint64; + } + + @Override + public test.xmlprimitives.data.Nullables setNSint64(Long value) { + internalSetNSint64(value); + return this; + } + + /** Internal setter for {@link #getNSint64()} without chain call utility. */ + protected final void internalSetNSint64(Long value) { + _listener.beforeSet(this, N_SINT_64__PROP, value); + _nSint64 = value; + _listener.afterChanged(this, N_SINT_64__PROP); + } + + @Override + public final boolean hasNSint64() { + return _nSint64 != null; + } + + @Override + public final Long getNUint64() { + return _nUint64; + } + + @Override + public test.xmlprimitives.data.Nullables setNUint64(Long value) { + internalSetNUint64(value); + return this; + } + + /** Internal setter for {@link #getNUint64()} without chain call utility. */ + protected final void internalSetNUint64(Long value) { + _listener.beforeSet(this, N_UINT_64__PROP, value); + _nUint64 = value; + _listener.afterChanged(this, N_UINT_64__PROP); + } + + @Override + public final boolean hasNUint64() { + return _nUint64 != null; + } + + @Override + public final Long getNFixed64() { + return _nFixed64; + } + + @Override + public test.xmlprimitives.data.Nullables setNFixed64(Long value) { + internalSetNFixed64(value); + return this; + } + + /** Internal setter for {@link #getNFixed64()} without chain call utility. */ + protected final void internalSetNFixed64(Long value) { + _listener.beforeSet(this, N_FIXED_64__PROP, value); + _nFixed64 = value; + _listener.afterChanged(this, N_FIXED_64__PROP); + } + + @Override + public final boolean hasNFixed64() { + return _nFixed64 != null; + } + + @Override + public final Long getNSfixed64() { + return _nSfixed64; + } + + @Override + public test.xmlprimitives.data.Nullables setNSfixed64(Long value) { + internalSetNSfixed64(value); + return this; + } + + /** Internal setter for {@link #getNSfixed64()} without chain call utility. */ + protected final void internalSetNSfixed64(Long value) { + _listener.beforeSet(this, N_SFIXED_64__PROP, value); + _nSfixed64 = value; + _listener.afterChanged(this, N_SFIXED_64__PROP); + } + + @Override + public final boolean hasNSfixed64() { + return _nSfixed64 != null; + } + + @Override + public final Float getNFloat() { + return _nFloat; + } + + @Override + public test.xmlprimitives.data.Nullables setNFloat(Float value) { + internalSetNFloat(value); + return this; + } + + /** Internal setter for {@link #getNFloat()} without chain call utility. */ + protected final void internalSetNFloat(Float value) { + _listener.beforeSet(this, N_FLOAT__PROP, value); + _nFloat = value; + _listener.afterChanged(this, N_FLOAT__PROP); + } + + @Override + public final boolean hasNFloat() { + return _nFloat != null; + } + + @Override + public final Double getNDouble() { + return _nDouble; + } + + @Override + public test.xmlprimitives.data.Nullables setNDouble(Double value) { + internalSetNDouble(value); + return this; + } + + /** Internal setter for {@link #getNDouble()} without chain call utility. */ + protected final void internalSetNDouble(Double value) { + _listener.beforeSet(this, N_DOUBLE__PROP, value); + _nDouble = value; + _listener.afterChanged(this, N_DOUBLE__PROP); + } + + @Override + public final boolean hasNDouble() { + return _nDouble != null; + } + + @Override + public final String getNString() { + return _nString; + } + + @Override + public test.xmlprimitives.data.Nullables setNString(String value) { + internalSetNString(value); + return this; + } + + /** Internal setter for {@link #getNString()} without chain call utility. */ + protected final void internalSetNString(String value) { + _listener.beforeSet(this, N_STRING__PROP, value); + _nString = value; + _listener.afterChanged(this, N_STRING__PROP); + } + + @Override + public final boolean hasNString() { + return _nString != null; + } + + @Override + public final byte[] getNBytes() { + return _nBytes; + } + + @Override + public test.xmlprimitives.data.Nullables setNBytes(byte[] value) { + internalSetNBytes(value); + return this; + } + + /** Internal setter for {@link #getNBytes()} without chain call utility. */ + protected final void internalSetNBytes(byte[] value) { + _listener.beforeSet(this, N_BYTES__PROP, value); + _nBytes = value; + _listener.afterChanged(this, N_BYTES__PROP); + } + + @Override + public final boolean hasNBytes() { + return _nBytes != null; + } + + @Override + public final Object getNJson() { + return _nJson; + } + + @Override + public test.xmlprimitives.data.Nullables setNJson(Object value) { + internalSetNJson(value); + return this; + } + + /** Internal setter for {@link #getNJson()} without chain call utility. */ + protected final void internalSetNJson(Object value) { + _listener.beforeSet(this, N_JSON__PROP, value); + _nJson = value; + _listener.afterChanged(this, N_JSON__PROP); + } + + @Override + public final boolean hasNJson() { + return _nJson != null; + } + + @Override + public final test.xmlprimitives.data.Color getNColor() { + return _nColor; + } + + @Override + public test.xmlprimitives.data.Nullables setNColor(test.xmlprimitives.data.Color value) { + internalSetNColor(value); + return this; + } + + /** Internal setter for {@link #getNColor()} without chain call utility. */ + protected final void internalSetNColor(test.xmlprimitives.data.Color value) { + _listener.beforeSet(this, N_COLOR__PROP, value); + _nColor = value; + _listener.afterChanged(this, N_COLOR__PROP); + } + + @Override + public final boolean hasNColor() { + return _nColor != null; + } + + @Override + public final java.util.List getNlInt32() { + return _nlInt32; + } + + @Override + public test.xmlprimitives.data.Nullables setNlInt32(java.util.List value) { + internalSetNlInt32(value); + return this; + } + + /** Internal setter for {@link #getNlInt32()} without chain call utility. */ + protected final void internalSetNlInt32(java.util.List value) { + if (_nlInt32 == null) _nlInt32 = new java.util.ArrayList<>(); + _nlInt32.clear(); + _nlInt32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Nullables addNlInt32(int value) { + internalAddNlInt32(value); + return this; + } + + /** Implementation of {@link #addNlInt32(int)} without chain call utility. */ + protected final void internalAddNlInt32(int value) { + if (_nlInt32 == null) _nlInt32 = new java.util.ArrayList<>(); + _nlInt32.add(value); + } + + @Override + public final void removeNlInt32(int value) { + if (_nlInt32 == null) _nlInt32 = new java.util.ArrayList<>(); + _nlInt32.remove(value); + } + + @Override + public final boolean hasNlInt32() { + return _nlInt32 != null; + } + + @Override + public final java.util.List getNlUint32() { + return _nlUint32; + } + + @Override + public test.xmlprimitives.data.Nullables setNlUint32(java.util.List value) { + internalSetNlUint32(value); + return this; + } + + /** Internal setter for {@link #getNlUint32()} without chain call utility. */ + protected final void internalSetNlUint32(java.util.List value) { + if (_nlUint32 == null) _nlUint32 = new java.util.ArrayList<>(); + _nlUint32.clear(); + _nlUint32.addAll(value); + } + + @Override + public test.xmlprimitives.data.Nullables addNlUint32(int value) { + internalAddNlUint32(value); + return this; + } + + /** Implementation of {@link #addNlUint32(int)} without chain call utility. */ + protected final void internalAddNlUint32(int value) { + if (_nlUint32 == null) _nlUint32 = new java.util.ArrayList<>(); + _nlUint32.add(value); + } + + @Override + public final void removeNlUint32(int value) { + if (_nlUint32 == null) _nlUint32 = new java.util.ArrayList<>(); + _nlUint32.remove(value); + } + + @Override + public final boolean hasNlUint32() { + return _nlUint32 != null; + } + + @Override + public final java.util.List getNlString() { + return _nlString; + } + + @Override + public test.xmlprimitives.data.Nullables setNlString(java.util.List value) { + internalSetNlString(value); + return this; + } + + /** Internal setter for {@link #getNlString()} without chain call utility. */ + protected final void internalSetNlString(java.util.List value) { + if (_nlString == null) _nlString = new java.util.ArrayList<>(); + _nlString.clear(); + _nlString.addAll(value); + } + + @Override + public test.xmlprimitives.data.Nullables addNlString(String value) { + internalAddNlString(value); + return this; + } + + /** Implementation of {@link #addNlString(String)} without chain call utility. */ + protected final void internalAddNlString(String value) { + if (_nlString == null) _nlString = new java.util.ArrayList<>(); + _nlString.add(value); + } + + @Override + public final void removeNlString(String value) { + if (_nlString == null) _nlString = new java.util.ArrayList<>(); + _nlString.remove(value); + } + + @Override + public final boolean hasNlString() { + return _nlString != null; + } + + @Override + public final java.util.List getNlBytes() { + return _nlBytes; + } + + @Override + public test.xmlprimitives.data.Nullables setNlBytes(java.util.List value) { + internalSetNlBytes(value); + return this; + } + + /** Internal setter for {@link #getNlBytes()} without chain call utility. */ + protected final void internalSetNlBytes(java.util.List value) { + if (_nlBytes == null) _nlBytes = new java.util.ArrayList<>(); + _nlBytes.clear(); + _nlBytes.addAll(value); + } + + @Override + public test.xmlprimitives.data.Nullables addNlByte(byte[] value) { + internalAddNlByte(value); + return this; + } + + /** Implementation of {@link #addNlByte(byte[])} without chain call utility. */ + protected final void internalAddNlByte(byte[] value) { + if (_nlBytes == null) _nlBytes = new java.util.ArrayList<>(); + _nlBytes.add(value); + } + + @Override + public final void removeNlByte(byte[] value) { + if (_nlBytes == null) _nlBytes = new java.util.ArrayList<>(); + _nlBytes.remove(value); + } + + @Override + public final boolean hasNlBytes() { + return _nlBytes != null; + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.xmlprimitives.data.Nullables registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.xmlprimitives.data.Nullables unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return NULLABLES__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + N_BOOL__PROP, + N_INT_32__PROP, + N_SINT_32__PROP, + N_UINT_32__PROP, + N_FIXED_32__PROP, + N_SFIXED_32__PROP, + N_INT_64__PROP, + N_SINT_64__PROP, + N_UINT_64__PROP, + N_FIXED_64__PROP, + N_SFIXED_64__PROP, + N_FLOAT__PROP, + N_DOUBLE__PROP, + N_STRING__PROP, + N_BYTES__PROP, + N_JSON__PROP, + N_COLOR__PROP, + NL_INT_32__PROP, + NL_UINT_32__PROP, + NL_STRING__PROP, + NL_BYTES__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case N_BOOL__PROP: return getNBool(); + case N_INT_32__PROP: return getNInt32(); + case N_SINT_32__PROP: return getNSint32(); + case N_UINT_32__PROP: return getNUint32(); + case N_FIXED_32__PROP: return getNFixed32(); + case N_SFIXED_32__PROP: return getNSfixed32(); + case N_INT_64__PROP: return getNInt64(); + case N_SINT_64__PROP: return getNSint64(); + case N_UINT_64__PROP: return getNUint64(); + case N_FIXED_64__PROP: return getNFixed64(); + case N_SFIXED_64__PROP: return getNSfixed64(); + case N_FLOAT__PROP: return getNFloat(); + case N_DOUBLE__PROP: return getNDouble(); + case N_STRING__PROP: return getNString(); + case N_BYTES__PROP: return getNBytes(); + case N_JSON__PROP: return getNJson(); + case N_COLOR__PROP: return getNColor(); + case NL_INT_32__PROP: return getNlInt32(); + case NL_UINT_32__PROP: return getNlUint32(); + case NL_STRING__PROP: return getNlString(); + case NL_BYTES__PROP: return getNlBytes(); + default: return test.xmlprimitives.data.Nullables.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case N_BOOL__PROP: internalSetNBool((Boolean) value); break; + case N_INT_32__PROP: internalSetNInt32((Integer) value); break; + case N_SINT_32__PROP: internalSetNSint32((Integer) value); break; + case N_UINT_32__PROP: internalSetNUint32((Integer) value); break; + case N_FIXED_32__PROP: internalSetNFixed32((Integer) value); break; + case N_SFIXED_32__PROP: internalSetNSfixed32((Integer) value); break; + case N_INT_64__PROP: internalSetNInt64((Long) value); break; + case N_SINT_64__PROP: internalSetNSint64((Long) value); break; + case N_UINT_64__PROP: internalSetNUint64((Long) value); break; + case N_FIXED_64__PROP: internalSetNFixed64((Long) value); break; + case N_SFIXED_64__PROP: internalSetNSfixed64((Long) value); break; + case N_FLOAT__PROP: internalSetNFloat((Float) value); break; + case N_DOUBLE__PROP: internalSetNDouble((Double) value); break; + case N_STRING__PROP: internalSetNString((String) value); break; + case N_BYTES__PROP: internalSetNBytes((byte[]) value); break; + case N_JSON__PROP: internalSetNJson((Object) value); break; + case N_COLOR__PROP: internalSetNColor((test.xmlprimitives.data.Color) value); break; + case NL_INT_32__PROP: internalSetNlInt32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case NL_UINT_32__PROP: internalSetNlUint32(de.haumacher.msgbuf.util.Conversions.asList(Integer.class, value)); break; + case NL_STRING__PROP: internalSetNlString(de.haumacher.msgbuf.util.Conversions.asList(String.class, value)); break; + case NL_BYTES__PROP: internalSetNlBytes(de.haumacher.msgbuf.util.Conversions.asList(byte[].class, value)); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + if (hasNBool()) { + out.name(N_BOOL__PROP); + out.value(getNBool()); + } + if (hasNInt32()) { + out.name(N_INT_32__PROP); + out.value(getNInt32()); + } + if (hasNSint32()) { + out.name(N_SINT_32__PROP); + out.value(getNSint32()); + } + if (hasNUint32()) { + out.name(N_UINT_32__PROP); + out.value(getNUint32()); + } + if (hasNFixed32()) { + out.name(N_FIXED_32__PROP); + out.value(getNFixed32()); + } + if (hasNSfixed32()) { + out.name(N_SFIXED_32__PROP); + out.value(getNSfixed32()); + } + if (hasNInt64()) { + out.name(N_INT_64__PROP); + out.value(getNInt64()); + } + if (hasNSint64()) { + out.name(N_SINT_64__PROP); + out.value(getNSint64()); + } + if (hasNUint64()) { + out.name(N_UINT_64__PROP); + out.value(getNUint64()); + } + if (hasNFixed64()) { + out.name(N_FIXED_64__PROP); + out.value(getNFixed64()); + } + if (hasNSfixed64()) { + out.name(N_SFIXED_64__PROP); + out.value(getNSfixed64()); + } + if (hasNFloat()) { + out.name(N_FLOAT__PROP); + out.value(getNFloat()); + } + if (hasNDouble()) { + out.name(N_DOUBLE__PROP); + out.value(getNDouble()); + } + if (hasNString()) { + out.name(N_STRING__PROP); + out.value(getNString()); + } + if (hasNBytes()) { + out.name(N_BYTES__PROP); + de.haumacher.msgbuf.json.JsonUtil.writeBinaryOptional(out, getNBytes()); + } + if (hasNJson()) { + out.name(N_JSON__PROP); + de.haumacher.msgbuf.json.JsonUtil.writeJsonValue(out, getNJson()); + } + if (hasNColor()) { + out.name(N_COLOR__PROP); + getNColor().writeTo(out); + } + if (hasNlInt32()) { + out.name(NL_INT_32__PROP); + out.beginArray(); + for (int x : getNlInt32()) { + out.value(x); + } + out.endArray(); + } + if (hasNlUint32()) { + out.name(NL_UINT_32__PROP); + out.beginArray(); + for (int x : getNlUint32()) { + out.value(x); + } + out.endArray(); + } + if (hasNlString()) { + out.name(NL_STRING__PROP); + out.beginArray(); + for (String x : getNlString()) { + out.value(x); + } + out.endArray(); + } + if (hasNlBytes()) { + out.name(NL_BYTES__PROP); + out.beginArray(); + for (byte[] x : getNlBytes()) { + de.haumacher.msgbuf.json.JsonUtil.writeBinaryOptional(out, x); + } + out.endArray(); + } + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case N_BOOL__PROP: setNBool(in.nextBoolean()); break; + case N_INT_32__PROP: setNInt32(in.nextInt()); break; + case N_SINT_32__PROP: setNSint32(in.nextInt()); break; + case N_UINT_32__PROP: setNUint32(in.nextInt()); break; + case N_FIXED_32__PROP: setNFixed32(in.nextInt()); break; + case N_SFIXED_32__PROP: setNSfixed32(in.nextInt()); break; + case N_INT_64__PROP: setNInt64(in.nextLong()); break; + case N_SINT_64__PROP: setNSint64(in.nextLong()); break; + case N_UINT_64__PROP: setNUint64(in.nextLong()); break; + case N_FIXED_64__PROP: setNFixed64(in.nextLong()); break; + case N_SFIXED_64__PROP: setNSfixed64(in.nextLong()); break; + case N_FLOAT__PROP: setNFloat((float) in.nextDouble()); break; + case N_DOUBLE__PROP: setNDouble(in.nextDouble()); break; + case N_STRING__PROP: setNString(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case N_BYTES__PROP: setNBytes(de.haumacher.msgbuf.json.JsonUtil.nextBinaryOptional(in)); break; + case N_JSON__PROP: setNJson(de.haumacher.msgbuf.json.JsonUtil.nextJsonValue(in)); break; + case N_COLOR__PROP: setNColor(test.xmlprimitives.data.Color.readColor(in)); break; + case NL_INT_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setNlInt32(newValue); + } + break; + case NL_UINT_32__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(in.nextInt()); + } + in.endArray(); + setNlUint32(newValue); + } + break; + case NL_STRING__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); + } + in.endArray(); + setNlString(newValue); + } + break; + case NL_BYTES__PROP: { + java.util.List newValue = new java.util.ArrayList<>(); + in.beginArray(); + while (in.hasNext()) { + newValue.add(de.haumacher.msgbuf.json.JsonUtil.nextBinaryOptional(in)); + } + in.endArray(); + setNlBytes(newValue); + } + break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + if (hasNBool()) { + out.name(N_BOOL__ID); + out.value(getNBool()); + } + if (hasNInt32()) { + out.name(N_INT_32__ID); + out.value(getNInt32()); + } + if (hasNSint32()) { + out.name(N_SINT_32__ID); + out.valueSigned(getNSint32()); + } + if (hasNUint32()) { + out.name(N_UINT_32__ID); + out.value(getNUint32()); + } + if (hasNFixed32()) { + out.name(N_FIXED_32__ID); + out.valueFixed(getNFixed32()); + } + if (hasNSfixed32()) { + out.name(N_SFIXED_32__ID); + out.valueFixed(getNSfixed32()); + } + if (hasNInt64()) { + out.name(N_INT_64__ID); + out.value(getNInt64()); + } + if (hasNSint64()) { + out.name(N_SINT_64__ID); + out.valueSigned(getNSint64()); + } + if (hasNUint64()) { + out.name(N_UINT_64__ID); + out.value(getNUint64()); + } + if (hasNFixed64()) { + out.name(N_FIXED_64__ID); + out.valueFixed(getNFixed64()); + } + if (hasNSfixed64()) { + out.name(N_SFIXED_64__ID); + out.valueFixed(getNSfixed64()); + } + if (hasNFloat()) { + out.name(N_FLOAT__ID); + out.value(getNFloat()); + } + if (hasNDouble()) { + out.name(N_DOUBLE__ID); + out.value(getNDouble()); + } + if (hasNString()) { + out.name(N_STRING__ID); + out.value(getNString()); + } + if (hasNBytes()) { + out.name(N_BYTES__ID); + out.value(getNBytes()); + } + if (hasNJson()) { + out.name(N_JSON__ID); + de.haumacher.msgbuf.json.JsonUtil.toJsonValue(getNJson()).writeTo(out); + } + if (hasNColor()) { + out.name(N_COLOR__ID); + getNColor().writeTo(out); + } + if (hasNlInt32()) { + out.name(NL_INT_32__ID); + { + java.util.List values = getNlInt32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (int x : values) { + out.value(x); + } + out.endArray(); + } + } + if (hasNlUint32()) { + out.name(NL_UINT_32__ID); + { + java.util.List values = getNlUint32(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.INT, values.size()); + for (int x : values) { + out.value(x); + } + out.endArray(); + } + } + if (hasNlString()) { + out.name(NL_STRING__ID); + { + java.util.List values = getNlString(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.STRING, values.size()); + for (String x : values) { + out.value(x); + } + out.endArray(); + } + } + if (hasNlBytes()) { + out.name(NL_BYTES__ID); + { + java.util.List values = getNlBytes(); + out.beginArray(de.haumacher.msgbuf.binary.DataType.BINARY, values.size()); + for (byte[] x : values) { + out.value(x); + } + out.endArray(); + } + } + } + + /** Helper for creating an object of type {@link test.xmlprimitives.data.Nullables} from a polymorphic composition. */ + public static test.xmlprimitives.data.Nullables readNullables_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Nullables_Impl result = new Nullables_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case N_BOOL__ID: setNBool(in.nextBoolean()); break; + case N_INT_32__ID: setNInt32(in.nextInt()); break; + case N_SINT_32__ID: setNSint32(in.nextIntSigned()); break; + case N_UINT_32__ID: setNUint32(in.nextInt()); break; + case N_FIXED_32__ID: setNFixed32(in.nextIntFixed()); break; + case N_SFIXED_32__ID: setNSfixed32(in.nextIntFixed()); break; + case N_INT_64__ID: setNInt64(in.nextLong()); break; + case N_SINT_64__ID: setNSint64(in.nextLongSigned()); break; + case N_UINT_64__ID: setNUint64(in.nextLong()); break; + case N_FIXED_64__ID: setNFixed64(in.nextLongFixed()); break; + case N_SFIXED_64__ID: setNSfixed64(in.nextLongFixed()); break; + case N_FLOAT__ID: setNFloat(in.nextFloat()); break; + case N_DOUBLE__ID: setNDouble(in.nextDouble()); break; + case N_STRING__ID: setNString(in.nextString()); break; + case N_BYTES__ID: setNBytes(in.nextBinary()); break; + case N_JSON__ID: setNJson(de.haumacher.msgbuf.json.JsonUtil.fromJsonValue(de.haumacher.msgbuf.json.value.JsonValue.readJsonValue(in))); break; + case N_COLOR__ID: setNColor(test.xmlprimitives.data.Color.readColor(in)); break; + case NL_INT_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addNlInt32(in.nextInt()); + } + in.endArray(); + } + break; + case NL_UINT_32__ID: { + in.beginArray(); + while (in.hasNext()) { + addNlUint32(in.nextInt()); + } + in.endArray(); + } + break; + case NL_STRING__ID: { + in.beginArray(); + while (in.hasNext()) { + addNlString(in.nextString()); + } + in.endArray(); + } + break; + case NL_BYTES__ID: { + in.beginArray(); + while (in.hasNext()) { + addNlByte(in.nextBinary()); + } + in.endArray(); + } + break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.xmlprimitives.data.Nullables} type. */ + public static final String NULLABLES__XML_ELEMENT = "nullables"; + + /** XML attribute or element name of a {@link #getNBool} property. */ + private static final String N_BOOL__XML_ATTR = "n-bool"; + + /** XML attribute or element name of a {@link #getNInt32} property. */ + private static final String N_INT_32__XML_ATTR = "n-int-32"; + + /** XML attribute or element name of a {@link #getNSint32} property. */ + private static final String N_SINT_32__XML_ATTR = "n-sint-32"; + + /** XML attribute or element name of a {@link #getNUint32} property. */ + private static final String N_UINT_32__XML_ATTR = "n-uint-32"; + + /** XML attribute or element name of a {@link #getNFixed32} property. */ + private static final String N_FIXED_32__XML_ATTR = "n-fixed-32"; + + /** XML attribute or element name of a {@link #getNSfixed32} property. */ + private static final String N_SFIXED_32__XML_ATTR = "n-sfixed-32"; + + /** XML attribute or element name of a {@link #getNInt64} property. */ + private static final String N_INT_64__XML_ATTR = "n-int-64"; + + /** XML attribute or element name of a {@link #getNSint64} property. */ + private static final String N_SINT_64__XML_ATTR = "n-sint-64"; + + /** XML attribute or element name of a {@link #getNUint64} property. */ + private static final String N_UINT_64__XML_ATTR = "n-uint-64"; + + /** XML attribute or element name of a {@link #getNFixed64} property. */ + private static final String N_FIXED_64__XML_ATTR = "n-fixed-64"; + + /** XML attribute or element name of a {@link #getNSfixed64} property. */ + private static final String N_SFIXED_64__XML_ATTR = "n-sfixed-64"; + + /** XML attribute or element name of a {@link #getNFloat} property. */ + private static final String N_FLOAT__XML_ATTR = "n-float"; + + /** XML attribute or element name of a {@link #getNDouble} property. */ + private static final String N_DOUBLE__XML_ATTR = "n-double"; + + /** XML attribute or element name of a {@link #getNString} property. */ + private static final String N_STRING__XML_ATTR = "n-string"; + + /** XML attribute or element name of a {@link #getNBytes} property. */ + private static final String N_BYTES__XML_ATTR = "n-bytes"; + + /** XML attribute or element name of a {@link #getNJson} property. */ + private static final String N_JSON__XML_ATTR = "n-json"; + + /** XML attribute or element name of a {@link #getNColor} property. */ + private static final String N_COLOR__XML_ATTR = "n-color"; + + /** XML attribute or element name of a {@link #getNlInt32} property. */ + private static final String NL_INT_32__XML_ATTR = "nl-int-32"; + + /** XML attribute or element name of a {@link #getNlUint32} property. */ + private static final String NL_UINT_32__XML_ATTR = "nl-uint-32"; + + /** XML attribute or element name of a {@link #getNlString} property. */ + private static final String NL_STRING__XML_ATTR = "nl-string"; + + /** XML attribute or element name of a {@link #getNlBytes} property. */ + private static final String NL_BYTES__XML_ATTR = "nl-bytes"; + + @Override + public String getXmlTagName() { + return NULLABLES__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + if (hasNBool()) { + out.writeAttribute(N_BOOL__XML_ATTR, Boolean.toString(getNBool())); + } + if (hasNInt32()) { + out.writeAttribute(N_INT_32__XML_ATTR, Integer.toString(getNInt32())); + } + if (hasNSint32()) { + out.writeAttribute(N_SINT_32__XML_ATTR, Integer.toString(getNSint32())); + } + if (hasNUint32()) { + out.writeAttribute(N_UINT_32__XML_ATTR, Long.toString(Integer.toUnsignedLong(getNUint32()))); + } + if (hasNFixed32()) { + out.writeAttribute(N_FIXED_32__XML_ATTR, Long.toString(Integer.toUnsignedLong(getNFixed32()))); + } + if (hasNSfixed32()) { + out.writeAttribute(N_SFIXED_32__XML_ATTR, Integer.toString(getNSfixed32())); + } + if (hasNInt64()) { + out.writeAttribute(N_INT_64__XML_ATTR, Long.toString(getNInt64())); + } + if (hasNSint64()) { + out.writeAttribute(N_SINT_64__XML_ATTR, Long.toString(getNSint64())); + } + if (hasNUint64()) { + out.writeAttribute(N_UINT_64__XML_ATTR, Long.toString(getNUint64())); + } + if (hasNFixed64()) { + out.writeAttribute(N_FIXED_64__XML_ATTR, Long.toString(getNFixed64())); + } + if (hasNSfixed64()) { + out.writeAttribute(N_SFIXED_64__XML_ATTR, Long.toString(getNSfixed64())); + } + if (hasNFloat()) { + out.writeAttribute(N_FLOAT__XML_ATTR, Float.toString(getNFloat())); + } + if (hasNDouble()) { + out.writeAttribute(N_DOUBLE__XML_ATTR, Double.toString(getNDouble())); + } + if (hasNString()) { + out.writeAttribute(N_STRING__XML_ATTR, getNString()); + } + if (hasNBytes()) { + out.writeAttribute(N_BYTES__XML_ATTR, java.util.Base64.getEncoder().encodeToString(getNBytes())); + } + out.writeAttribute(N_JSON__XML_ATTR, de.haumacher.msgbuf.json.JsonUtil.jsonStringValue(getNJson())); + if (hasNColor()) { + out.writeAttribute(N_COLOR__XML_ATTR, getNColor().protocolName()); + } + if (hasNlInt32()) { + out.writeAttribute(NL_INT_32__XML_ATTR, getNlInt32().stream().map(x -> Integer.toString(x)).collect(java.util.stream.Collectors.joining(", "))); + } + if (hasNlUint32()) { + out.writeAttribute(NL_UINT_32__XML_ATTR, getNlUint32().stream().map(x -> Long.toString(Integer.toUnsignedLong(x))).collect(java.util.stream.Collectors.joining(", "))); + } + if (hasNlString()) { + out.writeAttribute(NL_STRING__XML_ATTR, getNlString().stream().map(x -> x).collect(java.util.stream.Collectors.joining(", "))); + } + if (hasNlBytes()) { + out.writeAttribute(NL_BYTES__XML_ATTR, getNlBytes().stream().map(x -> java.util.Base64.getEncoder().encodeToString(x)).collect(java.util.stream.Collectors.joining(", "))); + } + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.xmlprimitives.data.Nullables} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Nullables_Impl readNullables_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Nullables_Impl result = new Nullables_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case N_BOOL__XML_ATTR: { + setNBool(Boolean.parseBoolean(value)); + break; + } + case N_INT_32__XML_ATTR: { + setNInt32(Integer.parseInt(value)); + break; + } + case N_SINT_32__XML_ATTR: { + setNSint32(Integer.parseInt(value)); + break; + } + case N_UINT_32__XML_ATTR: { + setNUint32((int) Long.parseLong(value)); + break; + } + case N_FIXED_32__XML_ATTR: { + setNFixed32((int) Long.parseLong(value)); + break; + } + case N_SFIXED_32__XML_ATTR: { + setNSfixed32(Integer.parseInt(value)); + break; + } + case N_INT_64__XML_ATTR: { + setNInt64(Long.parseLong(value)); + break; + } + case N_SINT_64__XML_ATTR: { + setNSint64(Long.parseLong(value)); + break; + } + case N_UINT_64__XML_ATTR: { + setNUint64(Long.parseLong(value)); + break; + } + case N_FIXED_64__XML_ATTR: { + setNFixed64(Long.parseLong(value)); + break; + } + case N_SFIXED_64__XML_ATTR: { + setNSfixed64(Long.parseLong(value)); + break; + } + case N_FLOAT__XML_ATTR: { + setNFloat(Float.parseFloat(value)); + break; + } + case N_DOUBLE__XML_ATTR: { + setNDouble(Double.parseDouble(value)); + break; + } + case N_STRING__XML_ATTR: { + setNString(value); + break; + } + case N_BYTES__XML_ATTR: { + setNBytes(java.util.Base64.getDecoder().decode(value)); + break; + } + case N_JSON__XML_ATTR: { + setNJson(de.haumacher.msgbuf.json.JsonUtil.parseJsonValue(value)); + break; + } + case N_COLOR__XML_ATTR: { + setNColor(test.xmlprimitives.data.Color.valueOfProtocol(value)); + break; + } + case NL_INT_32__XML_ATTR: { + setNlInt32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_UINT_32__XML_ATTR: { + setNlUint32(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_STRING__XML_ATTR: { + setNlString(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_BYTES__XML_ATTR: { + setNlBytes(java.util.Arrays.stream(value.isEmpty() ? new String[0] : value.split("\\s*,\\s*")).map(x -> java.util.Base64.getDecoder().decode(x)).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case N_BOOL__XML_ATTR: { + setNBool(Boolean.parseBoolean(in.getElementText())); + break; + } + case N_INT_32__XML_ATTR: { + setNInt32(Integer.parseInt(in.getElementText())); + break; + } + case N_SINT_32__XML_ATTR: { + setNSint32(Integer.parseInt(in.getElementText())); + break; + } + case N_UINT_32__XML_ATTR: { + setNUint32((int) Long.parseLong(in.getElementText())); + break; + } + case N_FIXED_32__XML_ATTR: { + setNFixed32((int) Long.parseLong(in.getElementText())); + break; + } + case N_SFIXED_32__XML_ATTR: { + setNSfixed32(Integer.parseInt(in.getElementText())); + break; + } + case N_INT_64__XML_ATTR: { + setNInt64(Long.parseLong(in.getElementText())); + break; + } + case N_SINT_64__XML_ATTR: { + setNSint64(Long.parseLong(in.getElementText())); + break; + } + case N_UINT_64__XML_ATTR: { + setNUint64(Long.parseLong(in.getElementText())); + break; + } + case N_FIXED_64__XML_ATTR: { + setNFixed64(Long.parseLong(in.getElementText())); + break; + } + case N_SFIXED_64__XML_ATTR: { + setNSfixed64(Long.parseLong(in.getElementText())); + break; + } + case N_FLOAT__XML_ATTR: { + setNFloat(Float.parseFloat(in.getElementText())); + break; + } + case N_DOUBLE__XML_ATTR: { + setNDouble(Double.parseDouble(in.getElementText())); + break; + } + case N_STRING__XML_ATTR: { + setNString(in.getElementText()); + break; + } + case N_BYTES__XML_ATTR: { + setNBytes(java.util.Base64.getDecoder().decode(in.getElementText())); + break; + } + case N_JSON__XML_ATTR: { + setNJson(de.haumacher.msgbuf.json.JsonUtil.parseJsonValue(in.getElementText())); + break; + } + case N_COLOR__XML_ATTR: { + setNColor(test.xmlprimitives.data.Color.valueOfProtocol(in.getElementText())); + break; + } + case NL_INT_32__XML_ATTR: { + String text = in.getElementText(); + setNlInt32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> Integer.parseInt(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_UINT_32__XML_ATTR: { + String text = in.getElementText(); + setNlUint32(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> (int) Long.parseLong(x)).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_STRING__XML_ATTR: { + String text = in.getElementText(); + setNlString(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> x).collect(java.util.stream.Collectors.toList())); + break; + } + case NL_BYTES__XML_ATTR: { + String text = in.getElementText(); + setNlBytes(java.util.Arrays.stream(text.isEmpty() ? new String[0] : text.split("\\s*,\\s*")).map(x -> java.util.Base64.getDecoder().decode(x)).collect(java.util.stream.Collectors.toList())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Values_Impl.java b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Values_Impl.java new file mode 100644 index 00000000..833d3f9d --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/data/impl/Values_Impl.java @@ -0,0 +1,926 @@ +package test.xmlprimitives.data.impl; + +/** + * Implementation of {@link test.xmlprimitives.data.Values}. + */ +public class Values_Impl extends de.haumacher.msgbuf.data.AbstractDataObject implements test.xmlprimitives.data.Values { + + private boolean _vBool = false; + + private int _vInt32 = 0; + + private int _vSint32 = 0; + + private int _vUint32 = 0; + + private int _vFixed32 = 0; + + private int _vSfixed32 = 0; + + private long _vInt64 = 0L; + + private long _vSint64 = 0L; + + private long _vUint64 = 0L; + + private long _vFixed64 = 0L; + + private long _vSfixed64 = 0L; + + private float _vFloat = 0.0f; + + private double _vDouble = 0.0d; + + private String _vString = ""; + + private byte[] _vBytes = null; + + private Object _vJson = null; + + private test.xmlprimitives.data.Color _vColor = test.xmlprimitives.data.Color.RED; + + /** + * Creates a {@link Values_Impl} instance. + * + * @see test.xmlprimitives.data.Values#create() + */ + public Values_Impl() { + super(); + } + + @Override + public final boolean isVBool() { + return _vBool; + } + + @Override + public test.xmlprimitives.data.Values setVBool(boolean value) { + internalSetVBool(value); + return this; + } + + /** Internal setter for {@link #isVBool()} without chain call utility. */ + protected final void internalSetVBool(boolean value) { + _listener.beforeSet(this, V_BOOL__PROP, value); + _vBool = value; + _listener.afterChanged(this, V_BOOL__PROP); + } + + @Override + public final int getVInt32() { + return _vInt32; + } + + @Override + public test.xmlprimitives.data.Values setVInt32(int value) { + internalSetVInt32(value); + return this; + } + + /** Internal setter for {@link #getVInt32()} without chain call utility. */ + protected final void internalSetVInt32(int value) { + _listener.beforeSet(this, V_INT_32__PROP, value); + _vInt32 = value; + _listener.afterChanged(this, V_INT_32__PROP); + } + + @Override + public final int getVSint32() { + return _vSint32; + } + + @Override + public test.xmlprimitives.data.Values setVSint32(int value) { + internalSetVSint32(value); + return this; + } + + /** Internal setter for {@link #getVSint32()} without chain call utility. */ + protected final void internalSetVSint32(int value) { + _listener.beforeSet(this, V_SINT_32__PROP, value); + _vSint32 = value; + _listener.afterChanged(this, V_SINT_32__PROP); + } + + @Override + public final int getVUint32() { + return _vUint32; + } + + @Override + public test.xmlprimitives.data.Values setVUint32(int value) { + internalSetVUint32(value); + return this; + } + + /** Internal setter for {@link #getVUint32()} without chain call utility. */ + protected final void internalSetVUint32(int value) { + _listener.beforeSet(this, V_UINT_32__PROP, value); + _vUint32 = value; + _listener.afterChanged(this, V_UINT_32__PROP); + } + + @Override + public final int getVFixed32() { + return _vFixed32; + } + + @Override + public test.xmlprimitives.data.Values setVFixed32(int value) { + internalSetVFixed32(value); + return this; + } + + /** Internal setter for {@link #getVFixed32()} without chain call utility. */ + protected final void internalSetVFixed32(int value) { + _listener.beforeSet(this, V_FIXED_32__PROP, value); + _vFixed32 = value; + _listener.afterChanged(this, V_FIXED_32__PROP); + } + + @Override + public final int getVSfixed32() { + return _vSfixed32; + } + + @Override + public test.xmlprimitives.data.Values setVSfixed32(int value) { + internalSetVSfixed32(value); + return this; + } + + /** Internal setter for {@link #getVSfixed32()} without chain call utility. */ + protected final void internalSetVSfixed32(int value) { + _listener.beforeSet(this, V_SFIXED_32__PROP, value); + _vSfixed32 = value; + _listener.afterChanged(this, V_SFIXED_32__PROP); + } + + @Override + public final long getVInt64() { + return _vInt64; + } + + @Override + public test.xmlprimitives.data.Values setVInt64(long value) { + internalSetVInt64(value); + return this; + } + + /** Internal setter for {@link #getVInt64()} without chain call utility. */ + protected final void internalSetVInt64(long value) { + _listener.beforeSet(this, V_INT_64__PROP, value); + _vInt64 = value; + _listener.afterChanged(this, V_INT_64__PROP); + } + + @Override + public final long getVSint64() { + return _vSint64; + } + + @Override + public test.xmlprimitives.data.Values setVSint64(long value) { + internalSetVSint64(value); + return this; + } + + /** Internal setter for {@link #getVSint64()} without chain call utility. */ + protected final void internalSetVSint64(long value) { + _listener.beforeSet(this, V_SINT_64__PROP, value); + _vSint64 = value; + _listener.afterChanged(this, V_SINT_64__PROP); + } + + @Override + public final long getVUint64() { + return _vUint64; + } + + @Override + public test.xmlprimitives.data.Values setVUint64(long value) { + internalSetVUint64(value); + return this; + } + + /** Internal setter for {@link #getVUint64()} without chain call utility. */ + protected final void internalSetVUint64(long value) { + _listener.beforeSet(this, V_UINT_64__PROP, value); + _vUint64 = value; + _listener.afterChanged(this, V_UINT_64__PROP); + } + + @Override + public final long getVFixed64() { + return _vFixed64; + } + + @Override + public test.xmlprimitives.data.Values setVFixed64(long value) { + internalSetVFixed64(value); + return this; + } + + /** Internal setter for {@link #getVFixed64()} without chain call utility. */ + protected final void internalSetVFixed64(long value) { + _listener.beforeSet(this, V_FIXED_64__PROP, value); + _vFixed64 = value; + _listener.afterChanged(this, V_FIXED_64__PROP); + } + + @Override + public final long getVSfixed64() { + return _vSfixed64; + } + + @Override + public test.xmlprimitives.data.Values setVSfixed64(long value) { + internalSetVSfixed64(value); + return this; + } + + /** Internal setter for {@link #getVSfixed64()} without chain call utility. */ + protected final void internalSetVSfixed64(long value) { + _listener.beforeSet(this, V_SFIXED_64__PROP, value); + _vSfixed64 = value; + _listener.afterChanged(this, V_SFIXED_64__PROP); + } + + @Override + public final float getVFloat() { + return _vFloat; + } + + @Override + public test.xmlprimitives.data.Values setVFloat(float value) { + internalSetVFloat(value); + return this; + } + + /** Internal setter for {@link #getVFloat()} without chain call utility. */ + protected final void internalSetVFloat(float value) { + _listener.beforeSet(this, V_FLOAT__PROP, value); + _vFloat = value; + _listener.afterChanged(this, V_FLOAT__PROP); + } + + @Override + public final double getVDouble() { + return _vDouble; + } + + @Override + public test.xmlprimitives.data.Values setVDouble(double value) { + internalSetVDouble(value); + return this; + } + + /** Internal setter for {@link #getVDouble()} without chain call utility. */ + protected final void internalSetVDouble(double value) { + _listener.beforeSet(this, V_DOUBLE__PROP, value); + _vDouble = value; + _listener.afterChanged(this, V_DOUBLE__PROP); + } + + @Override + public final String getVString() { + return _vString; + } + + @Override + public test.xmlprimitives.data.Values setVString(String value) { + internalSetVString(value); + return this; + } + + /** Internal setter for {@link #getVString()} without chain call utility. */ + protected final void internalSetVString(String value) { + _listener.beforeSet(this, V_STRING__PROP, value); + _vString = value; + _listener.afterChanged(this, V_STRING__PROP); + } + + @Override + public final byte[] getVBytes() { + return _vBytes; + } + + @Override + public test.xmlprimitives.data.Values setVBytes(byte[] value) { + internalSetVBytes(value); + return this; + } + + /** Internal setter for {@link #getVBytes()} without chain call utility. */ + protected final void internalSetVBytes(byte[] value) { + _listener.beforeSet(this, V_BYTES__PROP, value); + _vBytes = value; + _listener.afterChanged(this, V_BYTES__PROP); + } + + @Override + public final Object getVJson() { + return _vJson; + } + + @Override + public test.xmlprimitives.data.Values setVJson(Object value) { + internalSetVJson(value); + return this; + } + + /** Internal setter for {@link #getVJson()} without chain call utility. */ + protected final void internalSetVJson(Object value) { + _listener.beforeSet(this, V_JSON__PROP, value); + _vJson = value; + _listener.afterChanged(this, V_JSON__PROP); + } + + @Override + public final boolean hasVJson() { + return _vJson != null; + } + + @Override + public final test.xmlprimitives.data.Color getVColor() { + return _vColor; + } + + @Override + public test.xmlprimitives.data.Values setVColor(test.xmlprimitives.data.Color value) { + internalSetVColor(value); + return this; + } + + /** Internal setter for {@link #getVColor()} without chain call utility. */ + protected final void internalSetVColor(test.xmlprimitives.data.Color value) { + if (value == null) throw new IllegalArgumentException("Property 'vColor' cannot be null."); + _listener.beforeSet(this, V_COLOR__PROP, value); + _vColor = value; + _listener.afterChanged(this, V_COLOR__PROP); + } + + protected de.haumacher.msgbuf.observer.Listener _listener = de.haumacher.msgbuf.observer.Listener.NONE; + + @Override + public test.xmlprimitives.data.Values registerListener(de.haumacher.msgbuf.observer.Listener l) { + internalRegisterListener(l); + return this; + } + + protected final void internalRegisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.register(_listener, l); + } + + @Override + public test.xmlprimitives.data.Values unregisterListener(de.haumacher.msgbuf.observer.Listener l) { + internalUnregisterListener(l); + return this; + } + + protected final void internalUnregisterListener(de.haumacher.msgbuf.observer.Listener l) { + _listener = de.haumacher.msgbuf.observer.Listener.unregister(_listener, l); + } + + @Override + public String jsonType() { + return VALUES__TYPE; + } + + static final java.util.List PROPERTIES; + static { + java.util.List local = java.util.Arrays.asList( + V_BOOL__PROP, + V_INT_32__PROP, + V_SINT_32__PROP, + V_UINT_32__PROP, + V_FIXED_32__PROP, + V_SFIXED_32__PROP, + V_INT_64__PROP, + V_SINT_64__PROP, + V_UINT_64__PROP, + V_FIXED_64__PROP, + V_SFIXED_64__PROP, + V_FLOAT__PROP, + V_DOUBLE__PROP, + V_STRING__PROP, + V_BYTES__PROP, + V_JSON__PROP, + V_COLOR__PROP); + PROPERTIES = java.util.Collections.unmodifiableList(local); + } + + static final java.util.Set TRANSIENT_PROPERTIES; + static { + java.util.HashSet tmp = new java.util.HashSet<>(); + tmp.addAll(java.util.Arrays.asList( + )); + TRANSIENT_PROPERTIES = java.util.Collections.unmodifiableSet(tmp); + } + + @Override + public java.util.List properties() { + return PROPERTIES; + } + + @Override + public java.util.Set transientProperties() { + return TRANSIENT_PROPERTIES; + } + + @Override + public Object get(String field) { + switch (field) { + case V_BOOL__PROP: return isVBool(); + case V_INT_32__PROP: return getVInt32(); + case V_SINT_32__PROP: return getVSint32(); + case V_UINT_32__PROP: return getVUint32(); + case V_FIXED_32__PROP: return getVFixed32(); + case V_SFIXED_32__PROP: return getVSfixed32(); + case V_INT_64__PROP: return getVInt64(); + case V_SINT_64__PROP: return getVSint64(); + case V_UINT_64__PROP: return getVUint64(); + case V_FIXED_64__PROP: return getVFixed64(); + case V_SFIXED_64__PROP: return getVSfixed64(); + case V_FLOAT__PROP: return getVFloat(); + case V_DOUBLE__PROP: return getVDouble(); + case V_STRING__PROP: return getVString(); + case V_BYTES__PROP: return getVBytes(); + case V_JSON__PROP: return getVJson(); + case V_COLOR__PROP: return getVColor(); + default: return test.xmlprimitives.data.Values.super.get(field); + } + } + + @Override + public void set(String field, Object value) { + switch (field) { + case V_BOOL__PROP: internalSetVBool((boolean) value); break; + case V_INT_32__PROP: internalSetVInt32((int) value); break; + case V_SINT_32__PROP: internalSetVSint32((int) value); break; + case V_UINT_32__PROP: internalSetVUint32((int) value); break; + case V_FIXED_32__PROP: internalSetVFixed32((int) value); break; + case V_SFIXED_32__PROP: internalSetVSfixed32((int) value); break; + case V_INT_64__PROP: internalSetVInt64((long) value); break; + case V_SINT_64__PROP: internalSetVSint64((long) value); break; + case V_UINT_64__PROP: internalSetVUint64((long) value); break; + case V_FIXED_64__PROP: internalSetVFixed64((long) value); break; + case V_SFIXED_64__PROP: internalSetVSfixed64((long) value); break; + case V_FLOAT__PROP: internalSetVFloat((float) value); break; + case V_DOUBLE__PROP: internalSetVDouble((double) value); break; + case V_STRING__PROP: internalSetVString((String) value); break; + case V_BYTES__PROP: internalSetVBytes((byte[]) value); break; + case V_JSON__PROP: internalSetVJson((Object) value); break; + case V_COLOR__PROP: internalSetVColor((test.xmlprimitives.data.Color) value); break; + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + writeContent(out); + } + + @Override + protected void writeFields(de.haumacher.msgbuf.json.JsonWriter out) throws java.io.IOException { + super.writeFields(out); + out.name(V_BOOL__PROP); + out.value(isVBool()); + out.name(V_INT_32__PROP); + out.value(getVInt32()); + out.name(V_SINT_32__PROP); + out.value(getVSint32()); + out.name(V_UINT_32__PROP); + out.value(getVUint32()); + out.name(V_FIXED_32__PROP); + out.value(getVFixed32()); + out.name(V_SFIXED_32__PROP); + out.value(getVSfixed32()); + out.name(V_INT_64__PROP); + out.value(getVInt64()); + out.name(V_SINT_64__PROP); + out.value(getVSint64()); + out.name(V_UINT_64__PROP); + out.value(getVUint64()); + out.name(V_FIXED_64__PROP); + out.value(getVFixed64()); + out.name(V_SFIXED_64__PROP); + out.value(getVSfixed64()); + out.name(V_FLOAT__PROP); + out.value(getVFloat()); + out.name(V_DOUBLE__PROP); + out.value(getVDouble()); + out.name(V_STRING__PROP); + out.value(getVString()); + out.name(V_BYTES__PROP); + de.haumacher.msgbuf.json.JsonUtil.writeBinaryOptional(out, getVBytes()); + if (hasVJson()) { + out.name(V_JSON__PROP); + de.haumacher.msgbuf.json.JsonUtil.writeJsonValue(out, getVJson()); + } + out.name(V_COLOR__PROP); + getVColor().writeTo(out); + } + + @Override + protected void readField(de.haumacher.msgbuf.json.JsonReader in, String field) throws java.io.IOException { + switch (field) { + case V_BOOL__PROP: setVBool(in.nextBoolean()); break; + case V_INT_32__PROP: setVInt32(in.nextInt()); break; + case V_SINT_32__PROP: setVSint32(in.nextInt()); break; + case V_UINT_32__PROP: setVUint32(in.nextInt()); break; + case V_FIXED_32__PROP: setVFixed32(in.nextInt()); break; + case V_SFIXED_32__PROP: setVSfixed32(in.nextInt()); break; + case V_INT_64__PROP: setVInt64(in.nextLong()); break; + case V_SINT_64__PROP: setVSint64(in.nextLong()); break; + case V_UINT_64__PROP: setVUint64(in.nextLong()); break; + case V_FIXED_64__PROP: setVFixed64(in.nextLong()); break; + case V_SFIXED_64__PROP: setVSfixed64(in.nextLong()); break; + case V_FLOAT__PROP: setVFloat((float) in.nextDouble()); break; + case V_DOUBLE__PROP: setVDouble(in.nextDouble()); break; + case V_STRING__PROP: setVString(de.haumacher.msgbuf.json.JsonUtil.nextStringOptional(in)); break; + case V_BYTES__PROP: setVBytes(de.haumacher.msgbuf.json.JsonUtil.nextBinaryOptional(in)); break; + case V_JSON__PROP: setVJson(de.haumacher.msgbuf.json.JsonUtil.nextJsonValue(in)); break; + case V_COLOR__PROP: setVColor(test.xmlprimitives.data.Color.readColor(in)); break; + default: super.readField(in, field); + } + } + + @Override + public final void writeTo(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.beginObject(); + writeFields(out); + out.endObject(); + } + + /** + * Serializes all fields of this instance to the given binary output. + * + * @param out + * The binary output to write to. + * @throws java.io.IOException If writing fails. + */ + protected void writeFields(de.haumacher.msgbuf.binary.DataWriter out) throws java.io.IOException { + out.name(V_BOOL__ID); + out.value(isVBool()); + out.name(V_INT_32__ID); + out.value(getVInt32()); + out.name(V_SINT_32__ID); + out.valueSigned(getVSint32()); + out.name(V_UINT_32__ID); + out.value(getVUint32()); + out.name(V_FIXED_32__ID); + out.valueFixed(getVFixed32()); + out.name(V_SFIXED_32__ID); + out.valueFixed(getVSfixed32()); + out.name(V_INT_64__ID); + out.value(getVInt64()); + out.name(V_SINT_64__ID); + out.valueSigned(getVSint64()); + out.name(V_UINT_64__ID); + out.value(getVUint64()); + out.name(V_FIXED_64__ID); + out.valueFixed(getVFixed64()); + out.name(V_SFIXED_64__ID); + out.valueFixed(getVSfixed64()); + out.name(V_FLOAT__ID); + out.value(getVFloat()); + out.name(V_DOUBLE__ID); + out.value(getVDouble()); + out.name(V_STRING__ID); + out.value(getVString()); + if (getVBytes() != null) { + out.name(V_BYTES__ID); + out.value(getVBytes()); + } + if (hasVJson()) { + out.name(V_JSON__ID); + de.haumacher.msgbuf.json.JsonUtil.toJsonValue(getVJson()).writeTo(out); + } + out.name(V_COLOR__ID); + getVColor().writeTo(out); + } + + /** Helper for creating an object of type {@link test.xmlprimitives.data.Values} from a polymorphic composition. */ + public static test.xmlprimitives.data.Values readValues_Content(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + test.xmlprimitives.data.impl.Values_Impl result = new Values_Impl(); + result.readContent(in); + return result; + } + + /** Helper for reading all fields of this instance. */ + protected final void readContent(de.haumacher.msgbuf.binary.DataReader in) throws java.io.IOException { + while (in.hasNext()) { + int field = in.nextName(); + readField(in, field); + } + } + + /** Consumes the value for the field with the given ID and assigns its value. */ + protected void readField(de.haumacher.msgbuf.binary.DataReader in, int field) throws java.io.IOException { + switch (field) { + case V_BOOL__ID: setVBool(in.nextBoolean()); break; + case V_INT_32__ID: setVInt32(in.nextInt()); break; + case V_SINT_32__ID: setVSint32(in.nextIntSigned()); break; + case V_UINT_32__ID: setVUint32(in.nextInt()); break; + case V_FIXED_32__ID: setVFixed32(in.nextIntFixed()); break; + case V_SFIXED_32__ID: setVSfixed32(in.nextIntFixed()); break; + case V_INT_64__ID: setVInt64(in.nextLong()); break; + case V_SINT_64__ID: setVSint64(in.nextLongSigned()); break; + case V_UINT_64__ID: setVUint64(in.nextLong()); break; + case V_FIXED_64__ID: setVFixed64(in.nextLongFixed()); break; + case V_SFIXED_64__ID: setVSfixed64(in.nextLongFixed()); break; + case V_FLOAT__ID: setVFloat(in.nextFloat()); break; + case V_DOUBLE__ID: setVDouble(in.nextDouble()); break; + case V_STRING__ID: setVString(in.nextString()); break; + case V_BYTES__ID: setVBytes(in.nextBinary()); break; + case V_JSON__ID: setVJson(de.haumacher.msgbuf.json.JsonUtil.fromJsonValue(de.haumacher.msgbuf.json.value.JsonValue.readJsonValue(in))); break; + case V_COLOR__ID: setVColor(test.xmlprimitives.data.Color.readColor(in)); break; + default: in.skipValue(); + } + } + + /** XML element name representing a {@link test.xmlprimitives.data.Values} type. */ + public static final String VALUES__XML_ELEMENT = "values"; + + /** XML attribute or element name of a {@link #isVBool} property. */ + private static final String V_BOOL__XML_ATTR = "v-bool"; + + /** XML attribute or element name of a {@link #getVInt32} property. */ + private static final String V_INT_32__XML_ATTR = "v-int-32"; + + /** XML attribute or element name of a {@link #getVSint32} property. */ + private static final String V_SINT_32__XML_ATTR = "v-sint-32"; + + /** XML attribute or element name of a {@link #getVUint32} property. */ + private static final String V_UINT_32__XML_ATTR = "v-uint-32"; + + /** XML attribute or element name of a {@link #getVFixed32} property. */ + private static final String V_FIXED_32__XML_ATTR = "v-fixed-32"; + + /** XML attribute or element name of a {@link #getVSfixed32} property. */ + private static final String V_SFIXED_32__XML_ATTR = "v-sfixed-32"; + + /** XML attribute or element name of a {@link #getVInt64} property. */ + private static final String V_INT_64__XML_ATTR = "v-int-64"; + + /** XML attribute or element name of a {@link #getVSint64} property. */ + private static final String V_SINT_64__XML_ATTR = "v-sint-64"; + + /** XML attribute or element name of a {@link #getVUint64} property. */ + private static final String V_UINT_64__XML_ATTR = "v-uint-64"; + + /** XML attribute or element name of a {@link #getVFixed64} property. */ + private static final String V_FIXED_64__XML_ATTR = "v-fixed-64"; + + /** XML attribute or element name of a {@link #getVSfixed64} property. */ + private static final String V_SFIXED_64__XML_ATTR = "v-sfixed-64"; + + /** XML attribute or element name of a {@link #getVFloat} property. */ + private static final String V_FLOAT__XML_ATTR = "v-float"; + + /** XML attribute or element name of a {@link #getVDouble} property. */ + private static final String V_DOUBLE__XML_ATTR = "v-double"; + + /** XML attribute or element name of a {@link #getVString} property. */ + private static final String V_STRING__XML_ATTR = "v-string"; + + /** XML attribute or element name of a {@link #getVBytes} property. */ + private static final String V_BYTES__XML_ATTR = "v-bytes"; + + /** XML attribute or element name of a {@link #getVJson} property. */ + private static final String V_JSON__XML_ATTR = "v-json"; + + /** XML attribute or element name of a {@link #getVColor} property. */ + private static final String V_COLOR__XML_ATTR = "v-color"; + + @Override + public String getXmlTagName() { + return VALUES__XML_ELEMENT; + } + + @Override + public final void writeContent(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + writeAttributes(out); + writeElements(out); + } + + /** Serializes all fields that are written as XML attributes. */ + protected void writeAttributes(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + out.writeAttribute(V_BOOL__XML_ATTR, Boolean.toString(isVBool())); + out.writeAttribute(V_INT_32__XML_ATTR, Integer.toString(getVInt32())); + out.writeAttribute(V_SINT_32__XML_ATTR, Integer.toString(getVSint32())); + out.writeAttribute(V_UINT_32__XML_ATTR, Long.toString(Integer.toUnsignedLong(getVUint32()))); + out.writeAttribute(V_FIXED_32__XML_ATTR, Long.toString(Integer.toUnsignedLong(getVFixed32()))); + out.writeAttribute(V_SFIXED_32__XML_ATTR, Integer.toString(getVSfixed32())); + out.writeAttribute(V_INT_64__XML_ATTR, Long.toString(getVInt64())); + out.writeAttribute(V_SINT_64__XML_ATTR, Long.toString(getVSint64())); + out.writeAttribute(V_UINT_64__XML_ATTR, Long.toString(getVUint64())); + out.writeAttribute(V_FIXED_64__XML_ATTR, Long.toString(getVFixed64())); + out.writeAttribute(V_SFIXED_64__XML_ATTR, Long.toString(getVSfixed64())); + out.writeAttribute(V_FLOAT__XML_ATTR, Float.toString(getVFloat())); + out.writeAttribute(V_DOUBLE__XML_ATTR, Double.toString(getVDouble())); + out.writeAttribute(V_STRING__XML_ATTR, getVString()); + if (getVBytes() != null) { + out.writeAttribute(V_BYTES__XML_ATTR, java.util.Base64.getEncoder().encodeToString(getVBytes())); + } + out.writeAttribute(V_JSON__XML_ATTR, de.haumacher.msgbuf.json.JsonUtil.jsonStringValue(getVJson())); + out.writeAttribute(V_COLOR__XML_ATTR, getVColor().protocolName()); + } + + /** Serializes all fields that are written as XML elements. */ + protected void writeElements(javax.xml.stream.XMLStreamWriter out) throws javax.xml.stream.XMLStreamException { + // No element fields. + } + + /** Creates a new {@link test.xmlprimitives.data.Values} and reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + public static Values_Impl readValues_XmlContent(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + Values_Impl result = new Values_Impl(); + result.readContentXml(in); + return result; + } + + /** Reads properties from the content (attributes and inner tags) of the currently open element in the given {@link javax.xml.stream.XMLStreamReader}. */ + protected final void readContentXml(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + for (int n = 0, cnt = in.getAttributeCount(); n < cnt; n++) { + String name = in.getAttributeLocalName(n); + String value = in.getAttributeValue(n); + + readFieldXmlAttribute(name, value); + } + while (true) { + int event = in.nextTag(); + if (event == javax.xml.stream.XMLStreamConstants.END_ELEMENT) { + break; + } + assert event == javax.xml.stream.XMLStreamConstants.START_ELEMENT; + + String localName = in.getLocalName(); + readFieldXmlElement(in, localName); + } + } + + /** Parses the given attribute value and assigns it to the field with the given name. */ + protected void readFieldXmlAttribute(String name, String value) { + switch (name) { + case V_BOOL__XML_ATTR: { + setVBool(Boolean.parseBoolean(value)); + break; + } + case V_INT_32__XML_ATTR: { + setVInt32(Integer.parseInt(value)); + break; + } + case V_SINT_32__XML_ATTR: { + setVSint32(Integer.parseInt(value)); + break; + } + case V_UINT_32__XML_ATTR: { + setVUint32((int) Long.parseLong(value)); + break; + } + case V_FIXED_32__XML_ATTR: { + setVFixed32((int) Long.parseLong(value)); + break; + } + case V_SFIXED_32__XML_ATTR: { + setVSfixed32(Integer.parseInt(value)); + break; + } + case V_INT_64__XML_ATTR: { + setVInt64(Long.parseLong(value)); + break; + } + case V_SINT_64__XML_ATTR: { + setVSint64(Long.parseLong(value)); + break; + } + case V_UINT_64__XML_ATTR: { + setVUint64(Long.parseLong(value)); + break; + } + case V_FIXED_64__XML_ATTR: { + setVFixed64(Long.parseLong(value)); + break; + } + case V_SFIXED_64__XML_ATTR: { + setVSfixed64(Long.parseLong(value)); + break; + } + case V_FLOAT__XML_ATTR: { + setVFloat(Float.parseFloat(value)); + break; + } + case V_DOUBLE__XML_ATTR: { + setVDouble(Double.parseDouble(value)); + break; + } + case V_STRING__XML_ATTR: { + setVString(value); + break; + } + case V_BYTES__XML_ATTR: { + setVBytes(java.util.Base64.getDecoder().decode(value)); + break; + } + case V_JSON__XML_ATTR: { + setVJson(de.haumacher.msgbuf.json.JsonUtil.parseJsonValue(value)); + break; + } + case V_COLOR__XML_ATTR: { + setVColor(test.xmlprimitives.data.Color.valueOfProtocol(value)); + break; + } + default: { + // Skip unknown attribute. + } + } + } + + /** Reads the element under the cursor and assigns its contents to the field with the given name. */ + protected void readFieldXmlElement(javax.xml.stream.XMLStreamReader in, String localName) throws javax.xml.stream.XMLStreamException { + switch (localName) { + case V_BOOL__XML_ATTR: { + setVBool(Boolean.parseBoolean(in.getElementText())); + break; + } + case V_INT_32__XML_ATTR: { + setVInt32(Integer.parseInt(in.getElementText())); + break; + } + case V_SINT_32__XML_ATTR: { + setVSint32(Integer.parseInt(in.getElementText())); + break; + } + case V_UINT_32__XML_ATTR: { + setVUint32((int) Long.parseLong(in.getElementText())); + break; + } + case V_FIXED_32__XML_ATTR: { + setVFixed32((int) Long.parseLong(in.getElementText())); + break; + } + case V_SFIXED_32__XML_ATTR: { + setVSfixed32(Integer.parseInt(in.getElementText())); + break; + } + case V_INT_64__XML_ATTR: { + setVInt64(Long.parseLong(in.getElementText())); + break; + } + case V_SINT_64__XML_ATTR: { + setVSint64(Long.parseLong(in.getElementText())); + break; + } + case V_UINT_64__XML_ATTR: { + setVUint64(Long.parseLong(in.getElementText())); + break; + } + case V_FIXED_64__XML_ATTR: { + setVFixed64(Long.parseLong(in.getElementText())); + break; + } + case V_SFIXED_64__XML_ATTR: { + setVSfixed64(Long.parseLong(in.getElementText())); + break; + } + case V_FLOAT__XML_ATTR: { + setVFloat(Float.parseFloat(in.getElementText())); + break; + } + case V_DOUBLE__XML_ATTR: { + setVDouble(Double.parseDouble(in.getElementText())); + break; + } + case V_STRING__XML_ATTR: { + setVString(in.getElementText()); + break; + } + case V_BYTES__XML_ATTR: { + setVBytes(java.util.Base64.getDecoder().decode(in.getElementText())); + break; + } + case V_JSON__XML_ATTR: { + setVJson(de.haumacher.msgbuf.json.JsonUtil.parseJsonValue(in.getElementText())); + break; + } + case V_COLOR__XML_ATTR: { + setVColor(test.xmlprimitives.data.Color.valueOfProtocol(in.getElementText())); + break; + } + default: { + internalSkipUntilMatchingEndElement(in); + } + } + } + + protected static final void internalSkipUntilMatchingEndElement(javax.xml.stream.XMLStreamReader in) throws javax.xml.stream.XMLStreamException { + int level = 0; + while (true) { + switch (in.next()) { + case javax.xml.stream.XMLStreamConstants.START_ELEMENT: level++; break; + case javax.xml.stream.XMLStreamConstants.END_ELEMENT: if (level == 0) { return; } else { level--; break; } + } + } + } + +} diff --git a/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/xmlprimitives.proto b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/xmlprimitives.proto new file mode 100644 index 00000000..ab8817cd --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/java/test/xmlprimitives/xmlprimitives.proto @@ -0,0 +1,77 @@ +syntax = "msgbuf"; + +/** + * All primitive types in all serialization formats, singular, repeated and nullable (issue #44). + */ +package test.xmlprimitives.data; + +enum Color { + RED; + GREEN; +} + +/** Every primitive type as singular field. */ +message Values { + bool vBool; + int32 vInt32; + sint32 vSint32; + uint32 vUint32; + fixed32 vFixed32; + sfixed32 vSfixed32; + int64 vInt64; + sint64 vSint64; + uint64 vUint64; + fixed64 vFixed64; + sfixed64 vSfixed64; + float vFloat; + double vDouble; + string vString; + bytes vBytes; + json vJson; + Color vColor; +} + +/** Every primitive type as repeated field. */ +message Lists { + repeated bool lBool; + repeated int32 lInt32; + repeated sint32 lSint32; + repeated uint32 lUint32; + repeated fixed32 lFixed32; + repeated sfixed32 lSfixed32; + repeated int64 lInt64; + repeated sint64 lSint64; + repeated uint64 lUint64; + repeated fixed64 lFixed64; + repeated sfixed64 lSfixed64; + repeated float lFloat; + repeated double lDouble; + repeated string lString; + repeated bytes lBytes; + repeated Color lColor; +} + +/** Every primitive type as nullable field. */ +message Nullables { + @Nullable bool nBool; + @Nullable int32 nInt32; + @Nullable sint32 nSint32; + @Nullable uint32 nUint32; + @Nullable fixed32 nFixed32; + @Nullable sfixed32 nSfixed32; + @Nullable int64 nInt64; + @Nullable sint64 nSint64; + @Nullable uint64 nUint64; + @Nullable fixed64 nFixed64; + @Nullable sfixed64 nSfixed64; + @Nullable float nFloat; + @Nullable double nDouble; + @Nullable string nString; + @Nullable bytes nBytes; + @Nullable json nJson; + @Nullable Color nColor; + @Nullable repeated int32 nlInt32; + @Nullable repeated uint32 nlUint32; + @Nullable repeated string nlString; + @Nullable repeated bytes nlBytes; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/issue.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/issue.proto new file mode 100644 index 00000000..6101ad9a --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/issue.proto @@ -0,0 +1,9 @@ +package reject.hierarchy.issue; + +/** The definition from the issue report (#45). */ +abstract message Msg { + abstract message Group extends Msg { } + message Item extends Group { int32 n; } +} + +message Item extends Msg { string s; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/base.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/base.proto new file mode 100644 index 00000000..75ddd66a --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/base.proto @@ -0,0 +1,5 @@ +package reject.hierarchy.open; + +option OpenWorld; + +abstract message Shape { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/one.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/one.proto new file mode 100644 index 00000000..82950e50 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/one.proto @@ -0,0 +1,5 @@ +package reject.hierarchy.one; + +import "base.proto"; + +message Circle extends reject.hierarchy.open.Shape { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/two.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/two.proto new file mode 100644 index 00000000..f88f0fcc --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/open/two.proto @@ -0,0 +1,5 @@ +package reject.hierarchy.two; + +import "base.proto"; + +message Circle extends reject.hierarchy.open.Shape { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/protocol.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/protocol.proto new file mode 100644 index 00000000..d4abf6f3 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/protocol.proto @@ -0,0 +1,35 @@ +package reject.hierarchy.protocol; + +option NoTypeKind; + +/** Equal identifiers given explicitly. */ +abstract message Shape { } + +@Name("shape") +message Circle extends Shape { } + +abstract message Polygon extends Shape { } + +@Name("shape") +message Square extends Polygon { } + +@XmlName("rect") +message Rect extends Polygon { } + +@XmlName("rect") +message Box extends Polygon { } + +@type_id(7) +message Line extends Shape { } + +@type_id(7) +message Arc extends Shape { } + +/** A concrete root carries no type information, equal type IDs do not matter. */ +message Plain { } + +@Name("x") +message Plain1 extends Plain { } + +@Name("x") +message Plain2 extends Plain { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/shadow.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/shadow.proto new file mode 100644 index 00000000..e683fc8e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/shadow.proto @@ -0,0 +1,18 @@ +package reject.hierarchy.shadow; + +option NoTypeKind; + +/** Messages named like nested definitions of their generalizations. */ +abstract message Base { + enum Kind { A; } + + message Item extends Base { } +} + +@Name("TopKind") +message Kind extends Base { } + +message Outer { + @Name("Outer.Item") + message Item extends Base { } +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/typekind.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/typekind.proto new file mode 100644 index 00000000..beb6ddcf --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/hierarchy/typekind.proto @@ -0,0 +1,21 @@ +package reject.hierarchy.typekind; + +/** Distinct type IDs, but the same TypeKind constant. */ +abstract message Msg { } + +message A { + @Name("A.Item") + message Item extends Msg { } +} + +message B { + message Item extends Msg { } +} + +/** A concrete root has a TypeKind enum, too. */ +message Root { } + +message FooBar extends Root { } + +@Name("Other") +message FOO_BAR extends Root { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/a/a.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/a/a.proto new file mode 100644 index 00000000..e0064bd7 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/a/a.proto @@ -0,0 +1,21 @@ +package reject.names.a; + +/** Uses the unqualified name 'Node', also defined in package 'reject.names.b' (issue #46). */ +message User { + Node node; + + message Inner { + repeated Node nodes; + } +} + +/** See {@link Node}. */ +enum Color { + RED; +} + +message Node { + string label; +} + +message Special extends Node { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/b/b.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/b/b.proto new file mode 100644 index 00000000..14ea4bd7 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/b/b.proto @@ -0,0 +1,5 @@ +package reject.names.b; + +message Node { + int32 id; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/c/c.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/c/c.proto new file mode 100644 index 00000000..bfe43945 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/c/c.proto @@ -0,0 +1,6 @@ +package reject.names.c; + +/** 'Node' is defined in two other packages, but not in this one. */ +message Use { + Node node; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/one.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/one.proto new file mode 100644 index 00000000..82462835 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/one.proto @@ -0,0 +1,3 @@ +package reject.names.dup; + +message Thing { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/twice.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/twice.proto new file mode 100644 index 00000000..dd20e63e --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/twice.proto @@ -0,0 +1,5 @@ +package reject.names.twice; + +message Thing { } + +enum Thing { A; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/two.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/two.proto new file mode 100644 index 00000000..82462835 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/dup/two.proto @@ -0,0 +1,3 @@ +package reject.names.dup; + +message Thing { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/lib.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/lib.proto new file mode 100644 index 00000000..fcec6fb1 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/lib.proto @@ -0,0 +1,3 @@ +package reject.names.imp; + +message Lib { } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/main.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/main.proto new file mode 100644 index 00000000..0e683635 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imp/main.proto @@ -0,0 +1,7 @@ +package reject.names.imp; + +import "lib.proto"; + +message Main { + Lib lib; +} diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/a/a.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/a/a.proto new file mode 100644 index 00000000..e65d03ce --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/a/a.proto @@ -0,0 +1,5 @@ +package reject.names.imports.a; + +message Node { string x; } + +message UseA { Node n; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/b/b.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/b/b.proto new file mode 100644 index 00000000..97bde57b --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/b/b.proto @@ -0,0 +1,3 @@ +package reject.names.imports.b; + +message Node { int32 y; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/c/c.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/c/c.proto new file mode 100644 index 00000000..c979f515 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/c/c.proto @@ -0,0 +1,6 @@ +package reject.names.imports.c; + +import "../a/a.proto"; + +/** Imports only 'a', so 'Node' is 'a.Node', whether or not 'b' is generated in the same run. */ +message UseC { Node n; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/d/d.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/d/d.proto new file mode 100644 index 00000000..95379466 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/d/d.proto @@ -0,0 +1,6 @@ +package reject.names.imports.d; + +import "../c/c.proto"; + +/** 'Node' is defined in 'a', which is imported indirectly (through 'c'). */ +message UseD { Node n; } diff --git a/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/e/e.proto b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/e/e.proto new file mode 100644 index 00000000..6b610b06 --- /dev/null +++ b/de.haumacher.msgbuf.generator/src/test/resources/reject/names/imports/e/e.proto @@ -0,0 +1,7 @@ +package reject.names.imports.e; + +import "../a/a.proto"; +import "../b/b.proto"; + +/** Both imported files define 'Node'. */ +message UseE { Node n; } diff --git a/de.haumacher.msgbuf/src/main/java/de/haumacher/msgbuf/binary/OctetDataReader.java b/de.haumacher.msgbuf/src/main/java/de/haumacher/msgbuf/binary/OctetDataReader.java index 153bdeaf..ac722008 100644 --- a/de.haumacher.msgbuf/src/main/java/de/haumacher/msgbuf/binary/OctetDataReader.java +++ b/de.haumacher.msgbuf/src/main/java/de/haumacher/msgbuf/binary/OctetDataReader.java @@ -479,7 +479,7 @@ private long readVarLong() throws IOException { if (data < 0) { throw new IOException("End of stream received, while reading var int."); } - result |= (data & MASK_7) << shift; + result |= ((long) (data & MASK_7)) << shift; if ((data & BIT_8) == 0) { return result; } diff --git a/de.haumacher.msgbuf/src/test/java/de/haumacher/msgbuf/binary/TestDataReaderWriter.java b/de.haumacher.msgbuf/src/test/java/de/haumacher/msgbuf/binary/TestDataReaderWriter.java index acc71d52..dfc63a66 100644 --- a/de.haumacher.msgbuf/src/test/java/de/haumacher/msgbuf/binary/TestDataReaderWriter.java +++ b/de.haumacher.msgbuf/src/test/java/de/haumacher/msgbuf/binary/TestDataReaderWriter.java @@ -43,6 +43,37 @@ public void readObject(OctetDataReader in) throws IOException { }); } + public void testVarLongMessage() throws IOException { + long[] values = { 0L, 1L, -1L, Integer.MAX_VALUE + 1L, 1L << 35, Long.MIN_VALUE, Long.MAX_VALUE }; + doTest(new IOTest() { + @Override + public void writeObject(OctetDataWriter out) throws IOException { + out.beginObject(); + int id = 1; + for (long value : values) { + out.name(id++); + out.value(value); + out.name(id++); + out.valueSigned(value); + } + out.endObject(); + } + + @Override + public void readObject(OctetDataReader in) throws IOException { + in.beginObject(); + int id = 1; + for (long value : values) { + assertEquals(id++, in.nextName()); + assertEquals(value, in.nextLong()); + assertEquals(id++, in.nextName()); + assertEquals(value, in.nextLongSigned()); + } + in.endObject(); + } + }); + } + public void testStringMessage() throws IOException { doTest(new IOTest() { @Override From 12b636f2b388c0496d87db66ffdbb97564ebc4a2 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 18:49:28 +0200 Subject: [PATCH 17/20] Prepare the changelog and README for release 1.3.0. The changes collected for 1.2.3 add the TypeScript helpers as a new feature, so the release is 1.3.0; the README's dependency snippets still named 1.2.1. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d758e540..c8aae8dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 1.2.3 +## 1.3.0 ### New Features - **TypeScript type definitions**: Generate a TypeScript module per `.proto` file describing its JSON diff --git a/README.md b/README.md index 221e78a0..e4d575cb 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ In contrast to `protobuf`, `msgbuf` supports: de.haumacher.msgbuf msgbuf-api - 1.2.1 + 1.3.0 ``` @@ -32,7 +32,7 @@ To the `build/plugins` section add: de.haumacher.msgbuf msgbuf-generator-maven-plugin - 1.2.1 + 1.3.0 @@ -172,7 +172,7 @@ or its imports. A package must not define a top-level name twice, not even in di ### Transient fields Fields marked with `transient` are not serialized in any format (JSON, binary, XML). They exist only in the in-memory -representation. Readers ignore values of transient fields, e.g. in XML documents written by versions before 1.2.3: +representation. Readers ignore values of transient fields, e.g. in XML documents written by versions before 1.3.0: ```protobuf message A { From b66de73aee53e2c97cd485dadd4b57b1e75db1f2 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 20:03:36 +0200 Subject: [PATCH 18/20] [maven-release-plugin] prepare release msgbuf-api-1.3.0 --- de.haumacher.msgbuf.generator/pom.xml | 4 ++-- de.haumacher.msgbuf/pom.xml | 2 +- msgbuf-generator-maven-plugin/pom.xml | 4 ++-- pom.xml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/de.haumacher.msgbuf.generator/pom.xml b/de.haumacher.msgbuf.generator/pom.xml index 059fc0bb..9eea572d 100644 --- a/de.haumacher.msgbuf.generator/pom.xml +++ b/de.haumacher.msgbuf.generator/pom.xml @@ -4,7 +4,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.2.3-SNAPSHOT + 1.3.0 msgbuf-generator @@ -34,7 +34,7 @@ de.haumacher.msgbuf msgbuf-api - 1.2.3-SNAPSHOT + 1.3.0 diff --git a/de.haumacher.msgbuf/pom.xml b/de.haumacher.msgbuf/pom.xml index 75f89722..6c49cb6c 100644 --- a/de.haumacher.msgbuf/pom.xml +++ b/de.haumacher.msgbuf/pom.xml @@ -4,7 +4,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.2.3-SNAPSHOT + 1.3.0 msgbuf-api diff --git a/msgbuf-generator-maven-plugin/pom.xml b/msgbuf-generator-maven-plugin/pom.xml index 22bbe1fc..e2b4d469 100644 --- a/msgbuf-generator-maven-plugin/pom.xml +++ b/msgbuf-generator-maven-plugin/pom.xml @@ -7,7 +7,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.2.3-SNAPSHOT + 1.3.0 msgbuf-generator-maven-plugin @@ -33,7 +33,7 @@ de.haumacher.msgbuf msgbuf-generator - 1.2.3-SNAPSHOT + 1.3.0 diff --git a/pom.xml b/pom.xml index 39d659b6..f45e0fa5 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.2.3-SNAPSHOT + 1.3.0 pom @@ -39,7 +39,7 @@ https://github.com/msgbuf/msgbuf scm:git:https://github.com/msgbuf/msgbuf.git scm:git:https://github.com/msgbuf/msgbuf.git - HEAD + msgbuf-api-1.3.0 From 2204051a9e3d6ec4b126986d3d4221c48e025cca Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 20:03:39 +0200 Subject: [PATCH 19/20] [maven-release-plugin] prepare for next development iteration --- de.haumacher.msgbuf.generator/pom.xml | 4 ++-- de.haumacher.msgbuf/pom.xml | 2 +- msgbuf-generator-maven-plugin/pom.xml | 4 ++-- pom.xml | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/de.haumacher.msgbuf.generator/pom.xml b/de.haumacher.msgbuf.generator/pom.xml index 9eea572d..3f38245b 100644 --- a/de.haumacher.msgbuf.generator/pom.xml +++ b/de.haumacher.msgbuf.generator/pom.xml @@ -4,7 +4,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.3.0 + 1.3.1-SNAPSHOT msgbuf-generator @@ -34,7 +34,7 @@ de.haumacher.msgbuf msgbuf-api - 1.3.0 + 1.3.1-SNAPSHOT diff --git a/de.haumacher.msgbuf/pom.xml b/de.haumacher.msgbuf/pom.xml index 6c49cb6c..e04e26e0 100644 --- a/de.haumacher.msgbuf/pom.xml +++ b/de.haumacher.msgbuf/pom.xml @@ -4,7 +4,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.3.0 + 1.3.1-SNAPSHOT msgbuf-api diff --git a/msgbuf-generator-maven-plugin/pom.xml b/msgbuf-generator-maven-plugin/pom.xml index e2b4d469..efb5242d 100644 --- a/msgbuf-generator-maven-plugin/pom.xml +++ b/msgbuf-generator-maven-plugin/pom.xml @@ -7,7 +7,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.3.0 + 1.3.1-SNAPSHOT msgbuf-generator-maven-plugin @@ -33,7 +33,7 @@ de.haumacher.msgbuf msgbuf-generator - 1.3.0 + 1.3.1-SNAPSHOT diff --git a/pom.xml b/pom.xml index f45e0fa5..3fc7b756 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ de.haumacher.msgbuf msgbuf-parent - 1.3.0 + 1.3.1-SNAPSHOT pom @@ -39,7 +39,7 @@ https://github.com/msgbuf/msgbuf scm:git:https://github.com/msgbuf/msgbuf.git scm:git:https://github.com/msgbuf/msgbuf.git - msgbuf-api-1.3.0 + HEAD From 63644046be374f5447f959528556a3687a8056a8 Mon Sep 17 00:00:00 2001 From: Bernhard Haumacher Date: Fri, 25 Sep 2026 20:33:14 +0200 Subject: [PATCH 20/20] Update the Central publishing plugin to 0.11.0. The 1.3.0 deployment was uploaded and published, but the release workflow failed while waiting for it: plugin 0.6.0 cannot parse the deployment status the Central Portal returns now (unknown property 'warnings'), so every future release would be reported as failed. Co-Authored-By: Claude Opus 5.5 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3fc7b756..478d1109 100644 --- a/pom.xml +++ b/pom.xml @@ -102,7 +102,7 @@ org.sonatype.central central-publishing-maven-plugin - 0.6.0 + 0.11.0 true central