feat(ext-jackson): one module per data format, bodies checked on the way in

flash-ext-jackson and flash-ext-validation become three modules:

- flash-ext-jackson-core: the Codec (one mapper, body/write/writeView),
  JacksonHandler, the outbound marshalling, and the constraint engine that
  used to be flash-ext-validation
- flash-ext-jackson-json: Json, JsonExtension, JsonHandler
- flash-ext-jackson-xml: Xml, XmlExtension, XmlHandler

Every Jackson format is the same databind model behind a different factory, so
the annotations, the constraints and the published schema are the same for all
of them: only the mapper and the content type differ, and that is all a format
module says. A route picks its format by the handler it extends — there is no
negotiation and nothing to configure.

A typed body is now always verified against its own type's jakarta
constraints, whatever the format: malformed is a 400, a broken constraint is a
422, and neither reaches the handler. The validator was already allocation-free
and stays so; validating is no longer something an application remembers to do.

bodyFrom is gone. body has the streaming semantics, because the request's
stream is reused per connection while bytes() allocates the whole body: one
name, the path that does not allocate. JacksonExtension is JsonExtension, and
autoJson() is auto().

The root POM now manages every module of this build, so anything composing
Flash imports it once and never names a version again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Zakaria El Orche
2026-09-23 13:31:28 +00:00
co-authored by Claude Opus 5
parent ef4740f26d
commit adcd6376b6
37 changed files with 894 additions and 801 deletions
@@ -0,0 +1,60 @@
# flash-ext-jackson-json
JSON bodies and JSON responses.
## Install
```java
JsonExtension json = new JsonExtension();
FlashApp.create(8080)
.install(json)
.use(json.auto())
.scan("com.acme.handlers")
.startAndBlock();
```
The default mapper discovers the modules on the classpath (Java Time among them) and writes dates
as ISO strings; `new JsonExtension(mapper)` takes one of your own. `auto()` serializes whatever a
handler returns, leaving alone what is already a response: `null`, a `Response`, a `byte[]` or a
`CharSequence`.
## A handler with a body
The body type is the handler's type argument, and that is the whole declaration — it is also what
the OpenAPI document describes and what the constraints are read from:
```java
@POST("/users")
public final class CreateUser extends JsonHandler<NewUser> {
@Inject private UserService users;
@Override protected Object handle(Request req, Response res, NewUser body) {
return users.create(body);
}
}
```
A malformed body never reaches it (400), nor does one that breaks a constraint (422).
## A handler that reads it itself
```java
public final class Import extends RequestHandler {
@Inject private Json json;
@Override public Object handle(Request req, Response res) throws Exception {
return archive.store(json.body(req, Manifest.class));
}
}
```
`Json` is the [`Codec`](../flash-ext-jackson-core) for `application/json`: `body`, `write`,
`writeView`, `mapper`.
## Notes
- One mapper per application (or per scope), shared by every handler; `ObjectMapper` is
thread-safe once configured.
- Install `flash-ext-jackson-xml` beside this one when an application speaks both: a route picks
its format by the handler it extends, not by negotiation.
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>dev.relism</groupId>
<artifactId>flash-extensions</artifactId>
<version>2.1.0-SNAPSHOT</version>
</parent>
<artifactId>flash-ext-jackson-json</artifactId>
<name>flash-ext-jackson-json</name>
<description>JSON bodies and responses: the Json codec, JsonHandler and the marshalling middleware.</description>
<dependencies>
<dependency>
<groupId>dev.relism</groupId>
<artifactId>flash-ext-jackson-core</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>dev.relism</groupId>
<artifactId>flash-testing</artifactId>
<scope>test</scope>
</dependency>
<!-- The constraints a body declares are described by the published document too. -->
<dependency>
<groupId>dev.relism</groupId>
<artifactId>flash-ext-openapi</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,27 @@
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.relism.flash.ext.jackson.Codec;
import dev.relism.flash.http.ContentType;
/**
* JSON in and out, checked against the body type's own constraints.
*
* <pre>{@code
* public final class CreateItem extends RequestHandler {
* @Inject private Json json;
*
* @Override public Object handle(Request req, Response res) throws Exception {
* return items.create(json.body(req, NewItem.class));
* }
* }
* }</pre>
*
* <p>A handler whose whole body is one type has nothing to write at all: see {@link JsonHandler}.
*/
public final class Json extends Codec {
public Json(ObjectMapper mapper) {
super(mapper, ContentType.JSON);
}
}
@@ -0,0 +1,50 @@
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import dev.relism.flash.ext.jackson.Marshalling;
import dev.relism.flash.extension.FlashContext;
import dev.relism.flash.extension.FlashExtension;
import dev.relism.flash.extension.FlashRegistrar;
import dev.relism.flash.http.ContentType;
import dev.relism.flash.routing.Middleware;
/**
* JSON for an application: the {@link Json} codec, the mapper behind it, and the middleware that
* serializes whatever a handler returns.
*
* <pre>{@code
* JsonExtension json = new JsonExtension();
* app.install(json).use(json.auto());
* }</pre>
*
* <p>The default mapper discovers the modules on the classpath (Java Time among them) and writes
* dates as ISO strings. Hand it a mapper of your own to decide otherwise.
*/
public class JsonExtension implements FlashExtension {
private final ObjectMapper mapper;
public JsonExtension() {
this(JsonMapper.builder()
.findAndAddModules()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build());
}
public JsonExtension(ObjectMapper mapper) {
this.mapper = mapper;
}
/** Serializes what a handler returns, unless it already returned a response, bytes or text. */
public Middleware auto() {
return Marshalling.of(mapper, ContentType.JSON);
}
@Override
public void configure(FlashRegistrar<?> app, FlashContext ctx) {
ctx.provide(Json.class, new Json(mapper));
ctx.provide(ObjectMapper.class, mapper);
}
}
@@ -0,0 +1,35 @@
package dev.relism.flash.ext.jackson.json;
import dev.relism.flash.ext.jackson.Codec;
import dev.relism.flash.ext.jackson.JacksonHandler;
import dev.relism.flash.extension.Inject;
import dev.relism.flash.http.ContentType;
import dev.relism.flash.routing.Consumes;
/**
* A handler that takes a JSON body of one type.
*
* <pre>{@code
* @POST("/users")
* public final class CreateUser extends JsonHandler<NewUser> {
* @Inject private UserService users;
*
* @Override protected Object handle(Request req, Response res, NewUser body) {
* return users.create(body);
* }
* }
* }</pre>
*
* <p>The body is read off the request stream, verified against the constraints its type declares,
* and handed over. A malformed body is a 400, a body that breaks a constraint is a 422, and
* neither ever reaches the handler. The published OpenAPI document describes the same type.
*/
@Consumes(ContentType.JSON)
public abstract class JsonHandler<B> extends JacksonHandler<B> {
@Inject private Json json;
@Override protected final Codec codec() {
return json;
}
}
@@ -1,6 +1,6 @@
package dev.relism.flash.ext.validation;
package dev.relism.flash.ext.jackson.json;
import dev.relism.flash.ext.jackson.JacksonExtension;
import dev.relism.flash.ext.jackson.json.JsonExtension;
import dev.relism.flash.ext.openapi.APIResponse;
import dev.relism.flash.ext.openapi.ApiOperation;
import dev.relism.flash.ext.openapi.Content;
@@ -24,7 +24,7 @@ import org.junit.jupiter.api.extension.RegisterExtension;
* describes them. Nothing registers this bridge — flash-ext-openapi picks the annotations up on
* its own when they are on the classpath.
*/
class ValidationOpenApiInteropTest {
class ConstraintsInTheDocumentTest {
record Account(
@NotBlank @Size(max = 40) String name,
@@ -42,10 +42,9 @@ class ValidationOpenApiInteropTest {
@RegisterExtension
static FlashTest app = FlashTest.of(configured -> {
configured.install(new JacksonExtension());
configured.install(new ValidationExtension());
configured.install(new OpenApiExtension("/openapi", "Accounts", "1.0.0"));
configured.scan("dev.relism.flash.ext.validation");
configured.install(new JsonExtension());
configured.install(new OpenApiExtension("/openapi", "Accounts", "1.0.0"));
configured.scan("dev.relism.flash.ext.jackson.json");
});
@Test
@@ -1,4 +1,4 @@
package dev.relism.flash.ext.jackson;
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.relism.flash.extension.FlashContext;
@@ -16,26 +16,25 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JacksonExtensionTest {
class JsonExtensionTest {
@Test
void configure_registers_json_mapper_and_middleware() {
FlashContext ctx = new FlashContext();
ObjectMapper mapper = new ObjectMapper();
JacksonExtension ext = new JacksonExtension(mapper);
JsonExtension ext = new JsonExtension(mapper);
ext.configure(null, ctx);
ctx.complete();
assertNotNull(ctx.require(Json.class));
assertNotNull(ctx.require(JacksonMiddleware.class));
assertSame(mapper, ctx.require(ObjectMapper.class));
}
@Test
void autoJson_factory_delegates_to_middleware_policy() throws Exception {
void auto_marshals_what_a_handler_returns() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JacksonExtension ext = new JacksonExtension(mapper);
JsonExtension ext = new JsonExtension(mapper);
RequestHandler next = new RequestHandler() {
@Override
public Object handle(Request request, Response response) {
@@ -43,7 +42,7 @@ class JacksonExtensionTest {
}
};
RequestHandler wrapped = new RequestHandler() {
private final SimpleHandler.FunctionalHandler delegate = ext.autoJson().wrap(next);
private final SimpleHandler.FunctionalHandler delegate = ext.auto().wrap(next);
@Override
public Object handle(Request request, Response response) throws Exception {
@@ -0,0 +1,78 @@
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.relism.flash.extension.FlashContext;
import dev.relism.flash.http.ContentType;
import dev.relism.flash.http.HttpMethod;
import dev.relism.flash.models.Http1HeaderMap;
import dev.relism.flash.models.Request;
import dev.relism.flash.models.RequestLine;
import dev.relism.flash.models.Response;
import dev.relism.flash.routing.routers.fastpathrouter.FastPathViews;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JsonHandlerTest {
public record NewUser(String name) {}
static final class Create extends JsonHandler<NewUser> {
@Override protected Object handle(Request request, Response response, NewUser body) {
return body.name();
}
}
@SuppressWarnings("rawtypes")
static final class Untyped extends JsonHandler {
@Override protected Object handle(Request request, Response response, Object body) {
return null;
}
}
@Test
void theBodyArrivesParsedAsTheTypeTheHandlerDeclares() throws Exception {
Create handler = new Create();
handler.bind(context());
Object answer = handler.handle(request("{\"name\":\"alice\"}"), new Response(200, ContentType.JSON));
assertEquals("alice", answer);
}
@Test
void aMalformedBodyIsTheUsualBadRequest() throws Exception {
Create handler = new Create();
handler.bind(context());
dev.relism.flash.exceptions.HttpException refused = assertThrows(dev.relism.flash.exceptions.HttpException.class,
() -> handler.handle(request("not json"), new Response(200, ContentType.JSON)));
assertEquals(400, refused.status());
}
@Test
void aHandlerThatNeverNamedItsBodyTypeIsRefusedAtBoot() {
IllegalStateException refused = assertThrows(IllegalStateException.class, Untyped::new);
assertTrue(refused.getMessage().contains("Handler<YourBody>"), refused.getMessage());
}
private static FlashContext context() {
FlashContext ctx = new FlashContext();
ctx.provide(Json.class, new Json(new ObjectMapper()));
ctx.complete();
return ctx;
}
private static Request request(String body) {
return new Request(new RequestLine(HttpMethod.POST,
new FastPathViews.StringByteView("/users"), null,
new FastPathViews.StringByteView("HTTP/1.1"), new Http1HeaderMap()),
body.getBytes(StandardCharsets.UTF_8));
}
}
@@ -1,4 +1,4 @@
package dev.relism.flash.ext.jackson;
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -37,16 +37,11 @@ class JsonTest {
}
@Test
void bodyFrom_parses_stream_and_maps_bad_payload_to_http_400() throws Exception {
void a_truncated_body_is_a_bad_request_too() throws Exception {
Json json = new Json(new ObjectMapper());
Request ok = request("{\"id\":\"u2\",\"name\":\"bob\"}");
UserDto dto = json.bodyFrom(ok, UserDto.class);
assertEquals("u2", dto.id);
assertEquals("bob", dto.name);
HttpException ex = assertThrows(HttpException.class, () -> json.body(request("["), UserDto.class));
Request bad = request("[");
HttpException ex = assertThrows(HttpException.class, () -> json.bodyFrom(bad, UserDto.class));
assertEquals(400, ex.status());
}
@@ -1,6 +1,8 @@
package dev.relism.flash.ext.jackson;
package dev.relism.flash.ext.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.relism.flash.ext.jackson.Marshalling;
import dev.relism.flash.routing.Middleware;
import dev.relism.flash.models.SimpleHandler;
import dev.relism.flash.http.ContentType;
import dev.relism.flash.models.Request;
@@ -16,13 +18,13 @@ import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JacksonMiddlewareTest {
class MarshallingTest {
private static final Request REQ = null;
@Test
void autoJson_marshalsPojo_toJsonBytes_and_setsJsonContentType() throws Exception {
JacksonMiddleware mw = new JacksonMiddleware(new ObjectMapper());
void marshalling_marshalsPojo_toJsonBytes_and_setsJsonContentType() throws Exception {
Middleware mw = Marshalling.of(new ObjectMapper(), ContentType.JSON);
RequestHandler wrapped = wrap(mw, new UserDto("u1", "alice"));
Response res = new Response(200, ContentType.TEXT_PLAIN);
@@ -34,8 +36,8 @@ class JacksonMiddlewareTest {
}
@Test
void autoJson_passThrough_for_response_string_charSequence_bytes_and_null() throws Exception {
JacksonMiddleware mw = new JacksonMiddleware(new ObjectMapper());
void marshalling_passThrough_for_response_string_charSequence_bytes_and_null() throws Exception {
Middleware mw = Marshalling.of(new ObjectMapper(), ContentType.JSON);
Response payloadResponse = new Response(201, ContentType.TEXT_PLAIN).body("ok");
RequestHandler wrappedResponse = wrap(mw, payloadResponse);
@@ -55,17 +57,17 @@ class JacksonMiddlewareTest {
}
@Test
void autoJson_wraps_serialization_errors_as_illegal_state() {
JacksonMiddleware mw = new JacksonMiddleware(new ObjectMapper());
void marshalling_wraps_serialization_errors_as_illegal_state() {
Middleware mw = Marshalling.of(new ObjectMapper(), ContentType.JSON);
RequestHandler wrapped = wrap(mw, new CyclicDto());
Response res = new Response(200, ContentType.TEXT_PLAIN);
IllegalStateException ex = assertThrows(IllegalStateException.class, () -> wrapped.handle(REQ, res));
assertEquals("application/json", new String(res.getContentType(), StandardCharsets.UTF_8));
assertTrue(ex.getMessage().startsWith("Failed to serialize handler result as JSON:"));
assertTrue(ex.getMessage().startsWith("Could not serialize"));
}
private static RequestHandler wrap(JacksonMiddleware mw, Object fixedReturn) {
private static RequestHandler wrap(Middleware mw, Object fixedReturn) {
RequestHandler next = new RequestHandler() {
@Override
public Object handle(Request request, Response response) {
@@ -73,7 +75,7 @@ class JacksonMiddlewareTest {
}
};
return new RequestHandler() {
private final SimpleHandler.FunctionalHandler delegate = mw.autoJson().wrap(next);
private final SimpleHandler.FunctionalHandler delegate = mw.wrap(next);
@Override
public Object handle(Request request, Response response) throws Exception {
@@ -1,6 +1,5 @@
package dev.relism.flash.ext.validation;
package dev.relism.flash.ext.jackson.json;
import dev.relism.flash.ext.jackson.JacksonExtension;
import dev.relism.flash.testing.FlashTest;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
@@ -12,19 +11,18 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** The whole path: JSON in, constraints checked, status out — with no error handling wired up. */
class ValidationRoutesTest {
class ValidatedBodyTest {
record CreateUser(@NotBlank @Size(max = 8) String name, @Email String email, @Min(18) int age) {}
@RegisterExtension
static FlashTest app = FlashTest.of(configured -> {
configured.install(new JacksonExtension());
configured.install(new ValidationExtension());
configured.install(new JsonExtension());
configured.ctx().onReady(() -> {
Validation validation = configured.ctx().require(Validation.class);
Json json = configured.ctx().require(Json.class);
configured.post("/users", (req, res) ->
res.status(201).body("created:" + validation.body(req, CreateUser.class).name()));
res.status(201).body("created:" + json.body(req, CreateUser.class).name()));
});
});