From 1a15e3c6deb8c0301b06e26694fee9bd321fc539 Mon Sep 17 00:00:00 2001 From: Othmane Ataallah Date: Fri, 18 Sep 2026 15:00:18 +0100 Subject: [PATCH] docs: human voice, community files, templates --- .github/ISSUE_TEMPLATE/bug_report.yml | 39 +++++++ .github/ISSUE_TEMPLATE/feature_request.yml | 21 ++++ .github/pull_request_template.md | 13 +++ CODE_OF_CONDUCT.md | 17 ++++ CONTRIBUTING.md | 37 +++++++ README.md | 113 ++++++++++----------- SECURITY.md | 16 +++ docs-site/docs/api.md | 12 +++ docs-site/docs/compatibility.md | 29 +++--- docs-site/docs/core.md | 40 ++++---- docs-site/docs/demos.md | 19 ++++ docs-site/docs/faq.md | 26 ++--- docs-site/docs/index.md | 25 +++-- docs-site/docs/jaxrs.md | 16 ++- docs-site/docs/json.md | 25 ++--- docs-site/docs/quickstart.md | 29 +++--- docs-site/docs/registry.md | 26 ++--- docs-site/docs/spring.md | 17 ++-- docs-site/docs/xml.md | 22 ++-- docs-site/mkdocs.yml | 2 + 20 files changed, 349 insertions(+), 195 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 docs-site/docs/api.md create mode 100644 docs-site/docs/demos.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..2c60ea6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,39 @@ +name: Bug report +description: Something broken, confusing, or surprising +labels: [bug] +body: + - type: input + id: version + attributes: + label: Library version + placeholder: e.g. 0.1.0 + validations: + required: true + - type: input + id: environment + attributes: + label: Environment + description: Java version, framework (Spring Boot / Jersey / plain Java), relevant dependency versions + placeholder: e.g. Java 21, Spring Boot 4.1, Jackson 3.2 + validations: + required: true + - type: textarea + id: expected + attributes: + label: What did you expect to happen? + validations: + required: true + - type: textarea + id: actual + attributes: + label: What happened instead? + description: Include the actual response body or stack trace if there is one + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Minimal reproduction + description: The smallest code snippet that shows the problem + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..7bc6ef0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,21 @@ +name: Feature request +description: An idea for the library +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve? + description: Describe the situation first — API ideas come second + validations: + required: true + - type: textarea + id: proposal + attributes: + label: What do you propose? + description: Sketch of the API or behavior, if you have one in mind + - type: textarea + id: alternatives + attributes: + label: What have you tried instead? + description: Workarounds you use today, or why existing options fall short diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..5ccbfab --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +# What this PR does + + + +## How it was checked + +- [ ] `./mvnw clean verify` passes locally (JDK 25) +- [ ] New behavior has tests; docs updated alongside +- [ ] No new runtime dependencies (or: new dependency justified below) + +## Notes for reviewers + + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..d13a558 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,17 @@ +# Code of Conduct + +This project aims to be a welcoming place for everyone interested in better HTTP error responses in Java. + +## The short version + +- Be kind and assume good intent. Critique code and ideas, never people. +- No harassment, hate speech, trolling, or unwelcome advances — in issues, pull requests, discussions, or anywhere representing the project. +- Disagreements about design are normal and healthy; keep them technical and specific. + +## Enforcement + +Unacceptable behavior can be reported privately to othmane.ataallah.dev@gmail.com. Reports are handled confidentially, and maintainers may warn, temporarily limit participation, or permanently remove offenders depending on severity. Retaliation against reporters is itself unacceptable. + +## Scope + +These rules apply everywhere the project lives: the repository, its issue tracker, pull requests, discussions, and the documentation site. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..120f321 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing + +Thanks for your interest in `problem-details-java`. Small, focused contributions beat big ones — a clear bug report is already a contribution. + +## How to help + +- **Use it and report back.** Real-world usage finds what tests miss: confusing APIs, missing docs, surprising behavior. +- **Report bugs** with a minimal reproduction (input, expected output, actual output, Java and dependency versions). +- **Suggest features** by describing the problem first; API proposals come second. +- **Fix things** via pull request (see below). + +## Working on the code + +Prerequisites: JDK 25 (pinned in `.sdkmanrc`) and the Maven wrapper — no other toolchain needed. + +```sh +./mvnw clean verify # full build, tests, format check +./mvnw spotless:apply # fix formatting (Google Java Style, enforced in CI) +``` + +Conventions that matter: + +- Java 17 is the compatibility floor: no newer language features or APIs in main code. +- `problem-details-core` stays dependency-free — framework or serialization imports there are a design discussion first, never a drive-by. +- Public API needs Javadoc, and behavior changes need tests. The bar is in `AGENTS.md`. +- One logical change per pull request, with tests and docs updated alongside. + +## Pull requests + +1. Fork, branch from `main` (`feat/...`, `fix/...`, `docs/...`, `chore/...`). +2. Keep the change tight; explain non-obvious design calls in the PR body. +3. Make sure `./mvnw clean verify` and the format check pass — CI runs both on JDK 17 and 25. +4. Maintainers merge with squash once CI is green and review is done. + +## Releases + +Only maintainers cut releases; the process is documented in `AGENTS.md`. If you need something released, open an issue and say so. diff --git a/README.md b/README.md index 0df90cd..6cdad83 100644 --- a/README.md +++ b/README.md @@ -1,89 +1,78 @@ # problem-details-java -A framework-agnostic Java implementation of [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457), *Problem Details for HTTP APIs*. +[![Build](https://github.com/othmaneataallah/problem-details-java/actions/workflows/build.yml/badge.svg)](https://github.com/othmaneataallah/problem-details-java/actions) +[![Maven Central](https://img.shields.io/maven-central/v/io.github.othmaneataallah/problem-details-core)](https://central.sonatype.com/search?q=g%3Aio.github.othmaneataallah) +[![License](https://img.shields.io/github/license/othmaneataallah/problem-details-java)](LICENSE) +[![Java](https://img.shields.io/badge/Java-17%2B-blue)](https://adoptium.net/) -The project provides a lightweight and extensible implementation with a dependency-free core and optional modules for JSON and XML serialization, a problem-type registry, and Spring and JAX-RS integrations. - -## Status - -All planned modules are implemented on `main`. The project versions as `0.1.0-SNAPSHOT` and has **not** been published to Maven Central yet; publishing is deliberately deferred until the codebase and testing are finalized. - -## Modules - -| Artifact | Description | -|-----------------------------------|-----------------------------------------------------------------------------------------------| -| `problem-details-core` | Dependency-free problem details model and API: immutable `ProblemDetail` + builder, typed extension keys (`ProblemDetailKey`), `ProblemDetailException` | -| `problem-details-jackson` | JSON serialization (`application/problem+json`) on Jackson 3 | -| `problem-details-xml` | XML serialization (`application/problem+xml`, RFC 9457 Appendix B) using only the JDK | -| `problem-details-registry` | IANA problem-type constants/helpers, `ProblemTypeRegistry`, custom problem-type support | -| `problem-details-spring` | Thin Spring MVC/WebFlux integration (Spring 7): converter plus a stack-agnostic `@ControllerAdvice` | -| `problem-details-jaxrs` | JAX-RS integration (Jakarta REST 4): `ExceptionMapper` and `MessageBodyWriter` for both media types | - -Group ID for all artifacts: `io.github.othmaneataallah`. - -## Usage - -Core model — no dependencies beyond the core artifact: +Ever returned an error from a Java API and wished every service did it the same way? [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) defines that way — a standard `type`, `title`, `status`, `detail`, and `instance` for HTTP errors. This library implements it for Java, so your APIs speak the same error language as everyone else's. ```java -ProblemDetail problem = ProblemDetail.builder() - .type("https://example.com/probs/out-of-credit") - .title("You do not have enough credit.") - .status(403) - .detail("Your current balance is 30, but that costs 50.") - .build(); +throw new ProblemDetailException( + ProblemDetail.builder() + .type("https://example.com/probs/out-of-credit") + .title("You do not have enough credit.") + .status(403) + .detail("Your current balance is 30, but that costs 50.") + .build()); ``` -JSON with Jackson 3: - -```java -JsonMapper mapper = JsonMapper.builder() - .addModule(new ProblemDetailsModule()) - .build(); -String json = mapper.writeValueAsString(problem); // application/problem+json -``` +Your clients get a proper `application/problem+json` response — no custom error formats to invent, document, or debug. -XML with the JDK only: +## Start here -```java -String xml = ProblemXml.toXml(problem); // application/problem+xml +```xml + + io.github.othmaneataallah + problem-details-core + 0.1.0 + ``` -Spring (register the advice explicitly, e.g. `@Import(ProblemDetailAdvice.class)`): - -```java -throw new ProblemDetailException(problem); // rendered as application/problem+json -``` +Then follow the [Quickstart](https://othmaneataallah.github.io/problem-details-java/quickstart/) — five minutes from empty project to first error response. Full guides live on the [documentation site](https://othmaneataallah.github.io/problem-details-java/). -See each module's `package-info.java` and the Javadoc for details, including extension members, the registry, and leniency rules. +## What's inside -## Requirements +| Module | What it does | +|---|---| +| `problem-details-core` | The model itself. No dependencies, no framework needed. | +| `problem-details-jackson` | Reads and writes `application/problem+json` (Jackson 3). | +| `problem-details-xml` | Reads and writes `application/problem+xml` (JDK only, nothing extra to install). | +| `problem-details-registry` | Reusable, documented error types instead of inventing your own. | +| `problem-details-spring` | One annotation and Spring MVC/WebFlux apps render errors correctly. | +| `problem-details-jaxrs` | Same for Jakarta REST, in JSON and XML. | -To **use** the library: Java 17+. +Custom fields (balances, validation errors, anything yours) are first-class and type-safe — see [Core concepts](https://othmaneataallah.github.io/problem-details-java/core/). -To **build** it: +## See it running -- JDK 25 (pinned in `.sdkmanrc`; artifacts still target Java 17) -- Maven via the wrapper: `./mvnw clean verify` +Two runnable demos ship in [`demo/`](demo/) — real apps using the released library, each with a script that checks every endpoint: -## Building and testing +- [`demo/spring-boot`](demo/spring-boot) — Spring Boot app: full errors, validation lists, registry use, status fallbacks. +- [`demo/jersey`](demo/jersey) — Jersey/Grizzly app: JSON *and* XML responses from the same code. ```sh -./mvnw clean verify # full build, tests, and format check (JDK 21+) -./mvnw spotless:apply # auto-fix formatting (google-java-format) +cd demo/spring-boot +../../mvnw spring-boot:run # in one shell +./verify.sh # in another — all checks should pass ``` -CI runs the same verification on JDK 17 and JDK 25. Java formatting is enforced by Spotless; see `AGENTS.md` for contributor conventions. +## Reference -## IntelliJ IDEA setup +- [Documentation site](https://othmaneataallah.github.io/problem-details-java/) — guides, compatibility notes, FAQ. +- [API docs (Javadoc)](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-core) — per module: `problem-details-core`, `problem-details-jackson`, `problem-details-xml`, `problem-details-registry`, `problem-details-spring`, `problem-details-jaxrs`. +- [Changelog](CHANGELOG.md). -No committed run configurations are needed (this is a library, not an application): +## Building it yourself + +You need JDK 25 to build (the code itself runs on Java 17+): + +```sh +./mvnw clean verify +``` -1. Open the project and set the Project SDK to JDK 25. -2. Under *Settings → Build Tools → Maven*, use the Maven wrapper. -3. Run the build from the Maven tool window (`clean verify`), or create personal (uncommitted) Maven run configurations for `clean verify` and `spotless:apply`. -4. Tests also run natively (right-click a test or class). For exact Google Java Style formatting, install the google-java-format plugin matching the version pinned in the root `pom.xml`, or run `./mvnw spotless:apply` before committing. +Want to help? Read [CONTRIBUTING.md](CONTRIBUTING.md) — bug reports with reproductions are the most valuable contribution. ## License -Licensed under the Apache License, Version 2.0 — see [LICENSE](LICENSE). +Apache License 2.0 — see [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ca4b7fb --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,16 @@ +# Security Policy + +This library deals with error responses, which sit close to information disclosure risks — reports are taken seriously. + +## Reporting a vulnerability + +**Do not open a public issue.** Email othmane.ataallah.dev@gmail.com with: + +- What is affected (module, version) and what an attacker could achieve. +- Steps to reproduce, ideally as a small test or snippet. + +You will get a response within a few days. Once a fix is agreed, it ships as a normal release and the reporter is credited unless they prefer otherwise. + +## Supported versions + +Only the latest release line receives security fixes. There are no long-term-support branches at this time. diff --git a/docs-site/docs/api.md b/docs-site/docs/api.md new file mode 100644 index 0000000..d86d369 --- /dev/null +++ b/docs-site/docs/api.md @@ -0,0 +1,12 @@ +# API reference + +The guides on this site show the common paths. For everything else — every class, method, and contract — read the Javadoc: + +- [`problem-details-core`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-core) — `ProblemDetail`, `ProblemDetailKey`, `ProblemDetailException` +- [`problem-details-jackson`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-jackson) — `ProblemDetailsModule`, serializer, deserializer +- [`problem-details-xml`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-xml) — `ProblemXml` +- [`problem-details-registry`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-registry) — `ProblemType`, `ProblemTypeRegistry` +- [`problem-details-spring`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-spring) — `SpringProblemDetails`, `ProblemDetailAdvice` +- [`problem-details-jaxrs`](https://javadoc.io/doc/io.github.othmaneataallah/problem-details-jaxrs) — writer and exception mapper + +These pages are generated from each release automatically. If a link above doesn't resolve yet, the newest release is still propagating — try again shortly. diff --git a/docs-site/docs/compatibility.md b/docs-site/docs/compatibility.md index 9fd4dde..6a67138 100644 --- a/docs-site/docs/compatibility.md +++ b/docs-site/docs/compatibility.md @@ -1,20 +1,19 @@ # Compatibility -Minimums that are tested, not guessed — CI builds and tests every change on both JDK 17 and JDK 25. +Tested combinations — CI builds and tests every change on JDK 17 and 25, so these are facts, not hopes. -| Concern | Version | -|------------------|----------------------------------------------------------------| -| Your runtime | Java 17+ | -| Build JDK | 25 (artifacts target Java 17) | -| JSON | Jackson 3 (`tools.jackson.core:jackson-databind`) | -| XML | JDK only — no third-party dependency | -| Spring module | Spring Framework 7 (`spring-web`); MVC and WebFlux both covered | -| JAX-RS module | Jakarta REST 4 API (`provided` scope) | -| Tests | JUnit 6 + AssertJ | +| You need | Version | +|-----------------------|----------------------------------------------------------------| +| Java to run it | 17 or newer | +| JSON | Jackson 3 | +| XML | Nothing extra (JDK only) | +| Spring module | Spring Framework 7, MVC or WebFlux | +| JAX-RS module | Jakarta REST 4 (your runtime provides it) | +| Tests (contributors) | JUnit 6 + AssertJ | -Notes and honest limits: +A few straight answers: -- **Jackson 2 is not supported.** Jackson 3 is the current major line and Spring Boot 4's default; Jackson 2 support is deprecated upstream. The JSON module is Jackson 3 only. -- **Spring 6 / Boot 3 are untested.** The Spring module builds against Spring 7, whose baseline is still Java 17 — but Boot 3's line is end-of-life, so upgrade rather than backport. -- **Jakarta REST 3.x runtimes** will likely run the JAX-RS module (the APIs used are unchanged), but only Jakarta 4 is tested. -- Snapshots (`0.2.0-SNAPSHOT`) are never published; releases are cut as version tags and staged on Maven Central. +- **Jackson 2? No.** Jackson 3 is the current major line and what Spring Boot 4 ships. Jackson 2 support is deprecated upstream — staying on it would date the library on arrival. +- **Spring Boot 3? Untested, and its line is end-of-life.** The Spring module builds against Spring 7, which still runs on Java 17, so upgrading Boot is the only sane path. +- **Jakarta REST 3.x?** Probably works (the APIs used haven't changed), but only version 4 is tested. +- **Snapshots?** Never published. Releases come as version tags on Maven Central. diff --git a/docs-site/docs/core.md b/docs-site/docs/core.md index 070b407..a56f5f9 100644 --- a/docs-site/docs/core.md +++ b/docs-site/docs/core.md @@ -1,26 +1,26 @@ # Core concepts -Artifact: `problem-details-core`. No runtime dependencies, no framework — plain Java 17 and up. +Artifact: `problem-details-core`. No dependencies, no framework — plain Java 17 and up. Everything else in this library builds on what's here. -## The five members +## The five fields -The model uses the RFC's names exactly. Nothing is renamed, nothing is added: +Errors have the same five fields everywhere, with the RFC's names: -| Member | Type | Meaning | If absent | -|------------|-----------|----------------------------------------------------------------|--------------------------| -| `type` | URI | Identifies the problem *type* (the reusable part) | `about:blank` (default) | -| `title` | String | Short, human-readable summary of the type | omitted | -| `status` | Integer | HTTP status code for this occurrence (advisory — the real status travels on the HTTP response line) | omitted | -| `detail` | String | Human-readable explanation of *this occurrence* (never parsed by machines) | omitted | -| `instance` | URI | Identifies *this occurrence* | omitted | +| Field | Example | Notes | +|------------|--------------------------------------------------|--------------------------------------------------------------| +| `type` | `https://example.com/probs/out-of-credit` | *What kind* of problem. A URI you control. Defaults to `about:blank`. | +| `title` | `You do not have enough credit.` | Short summary. Same for every occurrence (translations aside). | +| `status` | `403` | The HTTP status. Handy to have inside the body, but the response line stays authoritative. | +| `detail` | `Your current balance is 30, but that costs 50.` | What happened *this time*. Written for humans, never parsed by machines. | +| `instance` | `/account/12345/msgs/abc` | Which occurrence this is. | -A useful mental split: `type` + `title` describe the *kind* of problem and stay stable across occurrences (except for localization); `status` + `detail` + `instance` describe *this time it happened*. +Think of it as two halves: `type` + `title` describe the *kind* of problem (stable, reusable), while `status` + `detail` + `instance` describe *this time it happened*. -`type` and `instance` accept plain strings too — `builder.type("https://example.com/probs/x")` parses them as URI references, including relative ones like `/types/out-of-credit`. +`type` and `instance` accept plain strings — relative references like `/types/out-of-credit` work fine. -## Typed extension members +## Your own fields -APIs usually need problem-specific data: a balance, a list of validation errors. Instead of an untyped map, each member gets a key that binds its name to its Java type: +Real errors carry their own data. Instead of a loose map, each field gets a key that pairs its name with its Java type, so reads are checked by the compiler: ```java ProblemDetailKey BALANCE = ProblemDetailKey.of("balance", Integer.class); @@ -29,21 +29,21 @@ ProblemDetail problem = ProblemDetail.builder() .extension(BALANCE, 30) .build(); -int balance = problem.get(BALANCE).orElseThrow(); // typed, no casts +int balance = problem.get(BALANCE).orElseThrow(); // no casts, ever ``` -Keys compare by name — the name is what identifies the member on the wire — so putting two values under one name keeps the last one. Lookups return `Optional`, and `has(key)` tests presence. Serializers see a read-only name-to-value view; application code should always use the typed API. +Missing fields come back empty (`Optional`), `has(key)` tests presence, and putting two values under one name keeps the last — the name is what identifies the field wherever it travels. -## Immutability +## Built problems never change -Built problems never change: the builder copies everything at `build()` time, exposed maps are unmodifiable, and there are no setters. Builders themselves are single-threaded by design — create them, build, and share the result freely. +Once built, a problem is frozen: no setters, and everything you read out is unmodifiable. Builders are single-use in spirit — build on one thread, share the result on all of them. ## Throwing problems -`ProblemDetailException` is an unchecked exception carrying a problem detail: +`ProblemDetailException` is an unchecked exception that carries the whole structured error: ```java throw new ProblemDetailException(problem); ``` -Its message is derived for plain stack traces (`detail`, else `title`, else `type`), but handlers should read `getProblemDetail()` — never parse the message. Both framework integrations map this exception to error responses automatically. +Handlers read `getProblemDetail()` — the exception message is only there so stack traces stay readable. The [Spring](spring.md) and [JAX-RS](jaxrs.md) integrations turn these exceptions into HTTP responses for you. diff --git a/docs-site/docs/demos.md b/docs-site/docs/demos.md new file mode 100644 index 0000000..65177b2 --- /dev/null +++ b/docs-site/docs/demos.md @@ -0,0 +1,19 @@ +# Demos + +Two small apps that run the released library end to end — the fastest way to see it behave, and to check your own setup against. + +Both live in [`demo/`](https://github.com/othmaneataallah/problem-details-java/tree/main/demo), build independently of the library, and ship a `verify.sh` script that starts nothing and assumes nothing: it waits for the app, curls every endpoint, and checks status codes, content types, and body fields. + +## Spring Boot demo + +[`demo/spring-boot`](https://github.com/othmaneataallah/problem-details-java/tree/main/demo/spring-boot) — a Spring Boot app showing the everyday cases: a full error with custom data, an error whose location fills in automatically, the 500 fallback, a validation-style error list, and the registry served as JSON. + +```sh +cd demo/spring-boot +../../mvnw spring-boot:run # in one shell +./verify.sh # in another +``` + +## Jersey demo + +[`demo/jersey`](https://github.com/othmaneataallah/problem-details-java/tree/main/demo/jersey) — a Jersey/Grizzly app on port 8081 (so both demos can run together). Same idea, plus the one thing only it can show: the same error served as JSON *or* XML depending on the `Accept` header. diff --git a/docs-site/docs/faq.md b/docs-site/docs/faq.md index c2e538b..e9d0afb 100644 --- a/docs-site/docs/faq.md +++ b/docs-site/docs/faq.md @@ -1,29 +1,25 @@ # FAQ -## Which modules do I need? +## Which pieces do I actually need? -`problem-details-core` always. Then add by output: `problem-details-jackson` for JSON, `problem-details-xml` for XML, one or both framework modules if you run Spring or Jakarta REST, `problem-details-registry` if you want reusable problem types. Nothing pulls anything you didn't ask for — the core stays dependency-free. +`problem-details-core`, always. Then add by output: the Jackson module for JSON, the XML module for XML, one framework module if you run Spring or Jakarta REST, the registry if you want reusable error types. Nothing drags in anything you didn't ask for. -## Why did my XML number come back as a string? +## Why did my XML number come back as text? -The XML format carries no types: `30` is text on the wire, so it reads back as `"30"`. This is inherent to RFC 9457, Appendix B, and the library deliberately never guesses — guessing would corrupt values like `"01234"`. If you need typed round-trips, use JSON. +Because in XML it *is* text: `30` carries no type information, so it reads back as `"30"`. That's how the RFC's XML format works, and nothing is guessed on the way back — which is also why values like `"01234"` survive intact. Need typed round-trips? Use JSON. -## Why is the error status 500 when my problem has no status? +## Why 500 when my error has no status? -An HTTP error response must carry a status code, but a problem detail may legitimately have none (outside an HTTP context, for example). Both framework integrations fall back to 500 Internal Server Error — and say so in their Javadoc. Set an explicit `status` if 500 misrepresents your error. Note the JAX-RS mapper keeps the body faithful (no status member), while Spring's rendering materializes the 500 into its own body object. +An HTTP error response needs a status code, and yours didn't name one — so both framework integrations answer 500. If that's misleading, set an explicit `status`. (Small difference between them: Jakarta keeps your body exactly as built; Spring's own object records the 500.) -## Why is `instance` filled in even though I never set it? +## I never set `instance`, yet responses have one. Why? -That's Spring, not this library: Spring defaults an absent `instance` from the request path. Set one explicitly and it passes through untouched. +That's Spring helping: it fills a missing `instance` from the request path. Set one yourself and yours wins. -## Where do I put problem-specific data? +## Where does my custom data go? -In typed extensions ([Core concepts](core.md#typed-extension-members)), and check the [Registry](registry.md) before inventing a new problem type. Never parse `detail` for machine-readable data — the RFC (Section 3.1.4) and this library agree: that's what extensions are for. - -## Can I use this with Jackson 2 / Spring Boot 3 / Java 11? - -Java 17 is the floor — no. Jackson 2 and Boot 3 are end-of-life lines; the library targets their successors (Jackson 3, Spring 7). See [Compatibility](compatibility.md). +In typed fields on the problem itself ([Core concepts](core.md#typed-extension-members)) — never by parsing `detail`. The detail string is for humans; machines read fields. And check the [Registry](registry.md) before inventing a whole new error type. ## Is it thread-safe? -Built problems, keys, types, and registries: yes, share freely. Builders: no — build on one thread, then share the result. `JsonMapper` is thread-safe once configured; `ProblemXml` is stateless. +Built errors, keys, types, and registries: yes, share them freely. Builders: no — build in one place, then share the result. A configured `JsonMapper` is thread-safe; the XML codec keeps no state at all. diff --git a/docs-site/docs/index.md b/docs-site/docs/index.md index cfabf33..563ee20 100644 --- a/docs-site/docs/index.md +++ b/docs-site/docs/index.md @@ -1,21 +1,20 @@ # problem-details-java -A framework-agnostic Java implementation of [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457), *Problem Details for HTTP APIs* — with a dependency-free core and optional modules for JSON and XML serialization, a problem-type registry, and Spring and JAX-RS integrations. +Standard error responses for Java APIs — one model, JSON and XML output, Spring and Jakarta REST support. -Use the tabs above to find your path. New here? Start with [Quickstart](quickstart.md) — you'll return your first problem response in about five minutes. +If your API returns errors (it does), this library makes them consistent: every error carries the same five fields defined by [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457), so clients only learn one format. New here? The [Quickstart](quickstart.md) gets you there in five minutes. -## What you get +## Pick your path -- One immutable model for all five RFC members, with a builder — [Core concepts](core.md). -- Typed extension members instead of stringly-typed maps. -- JSON (`application/problem+json`) on Jackson 3 and XML (`application/problem+xml`) with no third-party dependencies — [JSON](json.md), [XML](xml.md). -- A problem-type registry for reuse instead of reinvention — [Registry](registry.md). -- One-line integrations for Spring MVC/WebFlux and Jakarta REST — [Spring](spring.md), [JAX-RS](jaxrs.md). +- **First time?** [Quickstart](quickstart.md), then [Core concepts](core.md). +- **Sending JSON?** [JSON](json.md). **Sending XML?** [XML](xml.md). +- **Using Spring?** [Spring](spring.md). **Using Jakarta REST?** [JAX-RS](jaxrs.md). +- **Reusing error types?** [Registry](registry.md). +- **Running it?** [Demos](demos.md) — two working apps you can start in a minute. +- **Looking something up?** [API reference](api.md), [Compatibility](compatibility.md), [FAQ](faq.md). -## Requirements +## At a glance -To **use** the library: Java 17 or newer. See [Compatibility](compatibility.md) for the exact dependency versions each module expects. +Works on **Java 17 and newer**. The core has no dependencies at all; each extra piece (JSON, Spring, …) is a module you add only if you need it. -## License - -Licensed under the Apache License, Version 2.0 — see [LICENSE](https://github.com/othmaneataallah/problem-details-java/blob/main/LICENSE). Something unclear? The [FAQ](faq.md) probably answers it. +Licensed under the Apache License 2.0 — see [LICENSE](https://github.com/othmaneataallah/problem-details-java/blob/main/LICENSE). diff --git a/docs-site/docs/jaxrs.md b/docs-site/docs/jaxrs.md index 5f711b1..38ca01e 100644 --- a/docs-site/docs/jaxrs.md +++ b/docs-site/docs/jaxrs.md @@ -1,8 +1,10 @@ # JAX-RS -Artifact: `problem-details-jaxrs` (Jakarta REST 4 — the API dependency is `provided` scope, so your runtime supplies it). Two standard providers; register them on your application however your implementation prefers (e.g. `Application` subclass): +Artifact: `problem-details-jaxrs` (Jakarta REST 4, API-only dependency — your runtime provides the rest). Two standard providers; register them on your application however your implementation likes (for example, an `Application` subclass). -- `ProblemDetailMessageBodyWriter` serializes problem details as `application/problem+json` or `application/problem+xml`, delegating to the Jackson and XML modules. Resources returning `ProblemDetail` negotiate both media types through the `Accept` header: +## Returning problems + +Return a problem from a resource and it negotiates like any other entity — JSON or XML depending on what the client asked for: ```java @GET @@ -12,4 +14,12 @@ public ProblemDetail get() { } ``` -- `ProblemDetailExceptionMapper` maps `ProblemDetailException` to error responses: status from the detail (500 fallback, same rule as Spring), body pinned to `application/problem+json` so error responses stay deterministic while normal resources still negotiate. +## Throwing problems + +Thrown problems always answer JSON, so error responses stay predictable no matter what the client accepts: + +```java +throw new ProblemDetailException(problem); +``` + +As with Spring, a problem without `status` answers 500 — with the body left exactly as you built it. diff --git a/docs-site/docs/json.md b/docs-site/docs/json.md index 91b3212..69b4b5c 100644 --- a/docs-site/docs/json.md +++ b/docs-site/docs/json.md @@ -1,10 +1,10 @@ # JSON -Artifact: `problem-details-jackson`. Media type: `application/problem+json`. Built on Jackson 3. +Artifact: `problem-details-jackson`. Media type: `application/problem+json`. Needs Jackson 3. ## Setup -Add the artifact next to `problem-details-core` (same group ID, same version), then register the module once on your mapper: +Add the artifact next to `problem-details-core` (same group ID, same version), then register the module once: ```java JsonMapper mapper = JsonMapper.builder() @@ -12,11 +12,11 @@ JsonMapper mapper = JsonMapper.builder() .build(); ``` -Without the module, Jackson sees an ordinary bean — register it; there is no auto-detection. +That one registration is what teaches Jackson the format — without it you get an ordinary bean dump. ## Writing -Members serialize in RFC order — `type`, `status`, `title`, `detail`, `instance` — followed by extensions in the order you put them. Absent members are omitted; `type` is always present because the core defaults it to `about:blank`: +Fields come out in the RFC's order, missing fields are simply left out, and your custom fields follow in the order you added them. (`type` is always there — the core fills in `about:blank` for you.) ```json { @@ -29,7 +29,7 @@ Members serialize in RFC order — `type`, `status`, `title`, `detail`, `instanc } ``` -Extension values use Jackson's default value serialization, so strings, numbers, booleans, lists, and maps all work, nested as deeply as you like. +Custom values can be strings, numbers, booleans, lists, or maps, nested as deeply as you like. ## Reading @@ -37,20 +37,9 @@ Extension values use Jackson's default value serialization, so strings, numbers, ProblemDetail problem = mapper.readValue(json, ProblemDetail.class); ``` -Reading is lenient, exactly as RFC 9457, Section 3.1 requires: a member with the wrong type is *ignored*, as if it weren't there. A string where `status` belongs, an unparseable URI, or a JSON `null` all fall back to absent (and `type` then falls back to `about:blank`). Out-of-range or fractional statuses are ignored the same way. +Reading forgives a lot, by design: a field with the wrong type is skipped as if it weren't there, JSON `null`s count as absent, and an out-of-range status is dropped. Unknown fields are never lost — they become extensions, so an older reader still round-trips a newer producer's output without damage. -Unknown members are never dropped — they become extensions, so parse/serialize round-trips are lossless and newer producers don't break older consumers. Extension values map to Java values as follows: - -| JSON | Java | -|--------------|-------------------------------------------------| -| string | `String` | -| integer | `Integer` (or `Long` past int range) | -| decimal | `Double` | -| boolean | `Boolean` | -| array | `ArrayList` | -| object | `LinkedHashMap` | - -Because extension lookup is name-based, you read values back through your own keys regardless of how they arrived: +Values land in natural Java types (strings stay strings, whole numbers become `Integer` or `Long`, decimals become `Double`, arrays become lists, objects become maps), and you read them back through your own keys: ```java problem.get(ProblemDetailKey.of("balance", Integer.class)) // Optional[30] diff --git a/docs-site/docs/quickstart.md b/docs-site/docs/quickstart.md index 107a1e9..1e89822 100644 --- a/docs-site/docs/quickstart.md +++ b/docs-site/docs/quickstart.md @@ -1,10 +1,10 @@ # Quickstart -This page takes you from an empty project to your first problem response. It uses the core module plus JSON output; every step also links to the full guide. +From empty project to your first standard error response in five minutes. -## 1. Add the dependencies +## 1. Add two dependencies -Maven (`pom.xml`): +Maven: ```xml @@ -19,16 +19,14 @@ Maven (`pom.xml`): ``` -Gradle (`build.gradle`): +Gradle: ```groovy implementation "io.github.othmaneataallah:problem-details-core:0.1.0" implementation "io.github.othmaneataallah:problem-details-jackson:0.1.0" ``` -The core has zero runtime dependencies and works with no web framework at all. - -## 2. Build a problem +## 2. Describe an error ```java ProblemDetail problem = ProblemDetail.builder() @@ -39,7 +37,7 @@ ProblemDetail problem = ProblemDetail.builder() .build(); ``` -All five members are optional. Leave `type` out and it defaults to `about:blank`, exactly as the RFC prescribes. Read [Core concepts](core.md) for what each member means. +Every field is optional. Skip `type` and it becomes `about:blank` — a blank problem with no special meaning, which is exactly what you want for one-off errors. [What each field means →](core.md) ## 3. Send it as JSON @@ -51,7 +49,7 @@ JsonMapper mapper = JsonMapper.builder() String json = mapper.writeValueAsString(problem); ``` -That produces `application/problem+json`: +Your client receives `application/problem+json`: ```json { @@ -62,16 +60,17 @@ That produces `application/problem+json`: } ``` -## 4. Throw it in your app +## 4. Throw it in a real app ```java throw new ProblemDetailException(problem); ``` -The exception carries the structured detail, so your handlers never parse message strings. In Spring, register `ProblemDetailAdvice` and you're done; in Jakarta REST, register the two providers. Details: [Spring](spring.md), [JAX-RS](jaxrs.md). +In Spring, one registered advice turns that into the HTTP response. In Jakarta REST, two registered providers do the same. No message parsing anywhere — the structured error travels with the exception. -## Where next +## What next? -- Problem-specific data (balances, validation errors)? [Core concepts](core.md#typed-extension-members), then [Registry](registry.md) to reuse a type instead of inventing one. -- XML output? [XML](xml.md). -- Something surprising? [FAQ](faq.md). +- Your errors carry extra data (balances, field errors)? [Core concepts](core.md) shows how to add typed fields. +- Reusing an error type instead of inventing one? [Registry](registry.md). +- XML instead of JSON? [XML](xml.md). +- Prefer learning by running? [Demos](demos.md). diff --git a/docs-site/docs/registry.md b/docs-site/docs/registry.md index 00513c0..2371631 100644 --- a/docs-site/docs/registry.md +++ b/docs-site/docs/registry.md @@ -1,23 +1,23 @@ # Registry -Artifact: `problem-details-registry`. Before inventing a problem type, check whether a reusable one exists — that's what the "HTTP Problem Types" registry of RFC 9457, Section 4.2 is for, and what this module models. +Artifact: `problem-details-registry`. Before inventing an error type, check whether a reusable one already exists — that's what this module is for. -## Look up first +## Look one up ```java -ProblemTypeRegistry registry = new ProblemTypeRegistry(); // preloaded with about:blank +ProblemTypeRegistry registry = new ProblemTypeRegistry(); // starts with about:blank Optional known = registry.lookup("https://example.com/probs/out-of-credit"); ``` -One-liner access to the spec-registered types (today, just `about:blank`) lives on `ProblemTypes`: +For the built-in ones there's an even shorter path: ```java -ProblemTypes.lookup("about:blank"); // Optional[ProblemType] +ProblemTypes.lookup("about:blank"); ``` -## Register your own +## Add your own -If nothing fits, mint a stable URI under your control, document it (type URI, title, status code — the RFC's required trio, Section 4), and register it: +Nothing suitable? Mint a stable URI under your own control, give it a title and a status, point at your docs — and register it so the rest of your code finds it in one place: ```java registry.register( @@ -25,12 +25,12 @@ registry.register( "You do not have enough credit.", 403, "https://example.com/docs/probs")); ``` -Each entry carries its type URI, title, recommended status (empty when a type has no recommendation, like `about:blank`), and a reference to its defining specification. +Each entry holds the type URI, a short title, the recommended status (empty when there is none, like `about:blank`), and a reference to wherever it's documented. -Three guarantees make registries safe to share: +Three things the registry guarantees so you can share it across your app: -- **Duplicates fail fast.** Registering an already-known URI throws instead of silently shadowing an entry — possibly someone else's IANA one. -- **Instances are independent.** Registering on one registry never affects another, and the shared `ProblemTypes` lookup is read-only. -- **Thread-safe.** Lookups and registrations can race; exactly one duplicate registration wins. +- **Typos can't shadow entries.** Registering an already-known URI fails loudly instead of quietly replacing something — possibly someone else's standard type. +- **Registries don't leak into each other.** Each instance is independent, and the shared `ProblemTypes` lookup is read-only. +- **Threads are fine.** Lookups and registrations can race safely. -A note on `about:blank`: its registered title, "See HTTP Status Code", is not a usable title. When you use that type, set the title to the status phrase of your response (`Not Found` for 404, localized if you like) — that's what the RFC asks for. +One subtlety about `about:blank`: its registered title, "See HTTP Status Code", is an instruction, not a title. When you use that type, set the title to your response's status phrase (`Not Found` for a 404, in the client's language if you like) — that's what the RFC asks for. diff --git a/docs-site/docs/spring.md b/docs-site/docs/spring.md index 7594e03..754394e 100644 --- a/docs-site/docs/spring.md +++ b/docs-site/docs/spring.md @@ -1,29 +1,28 @@ # Spring -Artifact: `problem-details-spring` (Spring Framework 7, `spring-web` only). Spring already renders RFC 9457 responses natively — this module bridges your immutable model into that pipeline instead of building a parallel one. +Artifact: `problem-details-spring` (Spring Framework 7). Spring already knows how to render standard errors — this module plugs your problems into that machinery instead of building a second one. ## Setup -Register the single advice explicitly. Component scanning doesn't reach into library packages, and there is deliberately no Boot auto-configuration keeping this thin: +Register one advice class. Component scanning won't find it inside the library, so say it explicitly: ```java @Import(ProblemDetailAdvice.class) ``` -The advice uses only `spring-web` types, so the same class serves **Spring MVC and Spring WebFlux** applications. +That's the whole setup. The same class works in Spring MVC and Spring WebFlux apps. ## Usage -Throw as usual — the advice maps the exception to an `application/problem+json` response: +Throw like anywhere else: ```java throw new ProblemDetailException(problem); ``` -What happens on the way out: +You get an `application/problem+json` response with your problem's status, fields, and custom data. Two details: -- The response status comes from the problem detail, or **500** when it has no `status` member (an error response must carry a status; the RFC defines none for status-less problems). -- Your typed extensions are copied into Spring's properties map for rendering. -- An absent `instance` is defaulted from the request path by Spring; an explicit one passes through untouched. +- **No status on the problem?** The response goes out as 500 — an error response needs a status, and yours didn't name one. Prefer an explicit `status` when 500 would mislead. +- **No instance on the problem?** Spring fills it in from the request path. Set one yourself and yours wins. -The `SpringProblemDetails` helper exposes the same conversion (`toSpringDetail`, `toResponseEntity`, `statusCode`) for handlers you write yourself. +The `SpringProblemDetails` helper offers the same conversion (`toSpringDetail`, `toResponseEntity`, `statusCode`) for handlers you write by hand. diff --git a/docs-site/docs/xml.md b/docs-site/docs/xml.md index 5876f0b..5d6c105 100644 --- a/docs-site/docs/xml.md +++ b/docs-site/docs/xml.md @@ -1,17 +1,17 @@ # XML -Artifact: `problem-details-xml`. Media type: `application/problem+xml`. No third-party dependencies — reading and writing use the XML streaming API built into the JDK. +Artifact: `problem-details-xml`. Media type: `application/problem+xml`. Nothing extra to install — reading and writing use the XML support already in the JDK. ```java String xml = ProblemXml.toXml(problem); ProblemDetail readBack = ProblemXml.fromXml(xml); ``` -`toXml`/`fromXml` overloads also accept raw `XMLStreamWriter`/`XMLStreamReader` for streaming pipelines. Everything throws the checked `XMLStreamException` on failure — one exception type for I/O problems, malformed input, and rejected content. +(Streaming variants taking `XMLStreamWriter`/`XMLStreamReader` exist for pipelines. Everything reports failures as the checked `XMLStreamException` — one exception type for all of it.) -## The format +## What the XML looks like -The output follows RFC 9457, Appendix B exactly: a `` root in the `urn:ietf:rfc:7807` namespace (kept from the obsoleted RFC 7807 — that odd-looking `7807` is correct), one child element per member in schema order, extensions after the standard members: +One child element per field, extensions after the standard ones: ```xml @@ -28,15 +28,13 @@ The output follows RFC 9457, Appendix B exactly: a `` root in the `urn: ``` -Extensions follow the appendix's convention: an element with children is an **object**, except an element whose children are all named **`i`**, which is an **array**. Supported value types are `String`, `Number`, `Boolean`, `Character`, `List`, and `Map` — anything else fails fast with a clear error, as do extension names that aren't valid XML element names. +Two things to know, both inherited from the format itself rather than this library: an element with children is an *object*, except one whose children are all named `i` — that's an *array*. And yes, the namespace really says `7807`: the RFC kept it from the older spec it replaced. -## Two honest asymmetries +Only `String`, numbers, booleans, lists, and maps can be written — anything else fails fast with a clear error instead of silent garbage. The same goes for field names that aren't valid XML. -These come from the format itself, not from this library: +## Two quirks worth knowing upfront -1. **Everything travels as text.** `30` reads back as the *string* `"30"`. No type guessing is applied — which also keeps values like `"01234"` intact. -2. **Empty containers have no representation.** An empty list or map writes as an empty element and reads back as an empty string. +1. **Numbers come back as strings.** XML carries no types, so `30` reads back as `"30"`. Nothing is guessed — which is also what keeps values like `"01234"` intact. If typed round-trips matter to you, use JSON. +2. **Empty lists and maps have no representation.** They write as an empty element and read back as an empty string. -## Reading rules - -Mirroring the JSON module: unparseable URIs, non-numeric or out-of-range statuses, and markup where a scalar belongs are ignored; unknown elements become extensions; scalar text is trimmed (insignificant whitespace is unavoidable in XML); the root must be a `problem` element. DTDs and external entities are disabled, so XML bomb input is rejected outright. +Otherwise reading is as forgiving as the JSON side: bad URIs, bad statuses, and markup where text belongs are skipped; unknown elements become extensions; stray whitespace is trimmed. And hostile input (entity bombs and the like) is rejected — DTDs and external entities stay off. diff --git a/docs-site/mkdocs.yml b/docs-site/mkdocs.yml index a209e66..e7a7cfb 100644 --- a/docs-site/mkdocs.yml +++ b/docs-site/mkdocs.yml @@ -36,5 +36,7 @@ nav: - Registry: registry.md - Spring: spring.md - JAX-RS: jaxrs.md + - Demos: demos.md - Compatibility: compatibility.md - FAQ: faq.md + - API reference: api.md