Chenile Transformation

Copied from [`chenile-core/docs/transformation.md`](https://github.com/ajapros/chenile-core/blob/main/docs/transformation.md) on 1 December 2026.

Chenile’s transformation subsystem is responsible for turning an incoming raw request body into the Java object that the target service method expects.

The framework is payload-agnostic. It ships with a JSON transformer, which is the default, but the transformation step is a configurable list of transformers. A deployable can add transformers for XML, CSV, form data, Protobuf or any other format, or replace JSON altogether, without touching the rest of the pipeline.

This document explains:

  • where transformation sits in the interceptor chain
  • how body type is chosen
  • how the list of transformers is configured (chenile.transformers)
  • how the default JSON transformer converts payloads into typed Java objects
  • how to plug in a transformer for another payload format
  • how subclass selection works
  • how annotation and JSON-based body-type selectors feed the same runtime behavior

Where transformation happens

In the interceptor chain defined in chenile-core/src/main/resources/org/chenile/core/chenile-core.xml, transformation happens in two consecutive steps:

  1. transformation-class-selector
  2. transformers-interpolation

That ordering matters:

  • first Chenile decides what Java type the body should become
  • then the configured transformers convert the raw payload into that type

transformers-interpolation is an interpolation: a placeholder that expands at runtime into the commands named in the chenile.transformers property. By default that property is jsonTransformer, so out of the box the step behaves exactly like a single JSON deserializer.

The main classes

The core classes are:

  • chenile-core/src/main/java/org/chenile/core/transform/TransformationClassSelector.java
  • chenile-core/src/main/java/org/chenile/core/interceptors/interpolations/TransformersInterpolation.java
  • chenile-core/src/main/java/org/chenile/core/transform/JsonTransformer.java

TransformationClassSelector determines exchange.bodyType.

TransformersInterpolation runs the transformers listed in chenile.transformers, in order.

JsonTransformer, the default transformer, reads:

  • exchange.body
  • exchange.bodyType

and replaces the raw JSON body with a typed Java object.

Type selection knows nothing about the payload format. A body type selector decides what the body should become; a transformer decides how to get there from a particular format. That is why the same selectors (subclass, workflow event, custom) work for every payload format.

Why type selection is separate from transformation

Chenile separates these steps because the target type is not always fixed.

Sometimes the target type is obvious from the operation definition:

  • operation input type is JsonData
  • transform JSON into JsonData

Sometimes the target type depends on request context:

  • a header determines the subtype
  • a path variable determines whether the payload is a Room or a Vehicle
  • the body itself contains a type discriminator

That is why Chenile first selects the target type and only then deserializes.

Any payload, JSON by default

The transformers are configured per deployable with a comma-separated list of Spring bean names:

# default: equivalent to leaving the property out
chenile.transformers=jsonTransformer

# an XML transformer in front of JSON
chenile.transformers=xmlTransformer,jsonTransformer

# a deployable that accepts only Protobuf
chenile.transformers=protobufTransformer

How the list behaves:

  • the transformers run in the order listed, at the transformation step, after bodyType has been computed
  • jsonTransformer (a JsonTransformer bean registered by ChenileCoreConfiguration) is the default
  • every name is resolved at startup, all or nothing; an unknown bean name fails the application with a ConfigurationException instead of failing the first request
  • the list applies to every entry point, because every transport (HTTP, MCP, events, MQTT, Kafka, proxies, scheduler) runs the same chenile-highway

Writing a transformer for another format

A transformer is a Spring bean implementing Command<ChenileExchange>, usually by extending BaseChenileInterceptor and overriding doPreProcessing. Its contract mirrors the JSON transformer:

  1. read exchange.getBodyType() and exchange.getBody(); do nothing if either is missing
  2. decide whether this payload is yours, typically from the Content-Type header (exchange.getHeader("Content-Type", "", String.class)) or from the body itself; if it is not, leave the exchange untouched so the next transformer can handle it
  3. convert the body into exchange.getBodyType() and call exchange.setBody(...)
  4. call exchange.setApiInvocation(null) so ServiceInvoker recomputes the method arguments
  5. throw a BadRequestException if the payload cannot be parsed
public class XmlTransformer extends BaseChenileInterceptor {
    private final XmlMapper xml = new XmlMapper();

    @Override
    protected void doPreProcessing(ChenileExchange exchange) {
        Object body = exchange.getBody();
        if (exchange.getBodyType() == null || !(body instanceof String text)) return;
        String contentType = exchange.getHeader("Content-Type", "", String.class);
        if (!contentType.contains("xml")) return;
        try {
            exchange.setBody(xml.readValue(text, exchange.getBodyType()));
            exchange.setApiInvocation(null);
        } catch (Exception e) {
            throw new BadRequestException("Cannot parse XML payload", e);
        }
    }
}
@Bean public XmlTransformer xmlTransformer() { return new XmlTransformer(); }

Ordering with the JSON transformer

JsonTransformer tries to parse every String body as JSON. So a transformer for another text format must be listed before jsonTransformer (or replace it), otherwise the JSON transformer will reject the payload with a bad request before yours runs. Once your transformer has produced a typed object, JsonTransformer sees a body that is already compatible with bodyType and leaves it alone.

Binary payloads (byte[], streams) are never touched by JsonTransformer, so a binary transformer can sit anywhere in the list.

Default type selection

If no body-type selector is configured, TransformationClassSelector uses:

  • OperationDefinition.input

and converts that class into a TypeReference, then stores it into exchange.bodyType.

That is the default path for most ordinary typed request bodies.

Custom body-type selectors

If a body-type selector exists, TransformationClassSelector executes it instead of defaulting directly to the operation input class.

The selector may come from:

  • service-definition JSON via bodyTypeSelectorComponentNames
  • annotations via @BodyTypeSelector

In both cases, the runtime result is the same:

  • OperationDefinition.bodyTypeSelector contains a command
  • TransformationClassSelector executes that command
  • the command updates exchange.bodyType

JSON path and annotation path converge here

JSON path

An operation can declare:

"bodyTypeSelectorComponentNames": ["s6BodyTypeSelector"]

During service initialization, AbstractServiceInitializer resolves these bean names into a command chain and stores it on the OperationDefinition.

Annotation path

A controller method can declare:

@BodyTypeSelector("subclassBodyTypeSelector")

During annotation-based registration, OperationDefinitionProducerBase resolves the annotation values into the same kind of command chain and stores it on the OperationDefinition.

Same result

After registration, both paths produce the same runtime structure:

  • OperationDefinition.bodyTypeSelector
  • OperationDefinition.bodyTypeSelectorComponentNames

So the transformation subsystem does not care whether the selector came from JSON or annotations.

The default JSON transformer

JSON deserialization happens in JsonTransformer.

It behaves like this:

  1. read exchange.bodyType
  2. read exchange.body
  3. if either is missing, do nothing
  4. if the body is not a JSON-shaped value (a String, Map, Collection or Jackson JsonNode), do nothing
  5. if the body is already an object compatible with the target type (including generic element types), do nothing
  6. otherwise, deserialize the JSON string (or convert the map/list/tree) into the target type using Jackson
  7. replace exchange.body with the typed object

It also clears exchange.apiInvocation so method arguments can be recomputed after transformation.

The mapper ignores unknown properties and nulls for primitives. If conversion fails, JsonTransformer throws a bad request exception (TYPE_MISMATCH, naming the service and operation).

Accepting maps, lists and JsonNode lets in-JVM callers (MCP tool arguments, events, local proxies) hand over a partially parsed payload and still get the same typing as an HTTP JSON body.

Subclass selection

The most interesting transformation feature in this repository is subclass support.

The main classes are:

  • chenile-core/src/main/java/org/chenile/core/transform/SubclassRegistry.java
  • chenile-core/src/main/java/org/chenile/core/transform/SubclassBodyTypeSelector.java

SubclassRegistry

SubclassRegistry maintains mappings like:

  • base class Vehicle
  • discriminator value car -> subclass Car
  • discriminator value truck -> subclass Truck

It expects the payload JSON to contain a top-level field named type.

SubclassBodyTypeSelector

This selector:

  1. starts from the operation input type or current body type
  2. inspects the raw JSON body
  3. asks SubclassRegistry whether a more specific subclass should be used
  4. if found, updates exchange.bodyType to that subclass

This is how Chenile can accept a generic service contract like Vehicle but still instantiate Car or Truck before invocation.

Concrete subclass example

The subclass example is in:

  • chenile-http/src/test/java/org/chenile/http/test/controller/CapacityController.java
  • chenile-http/src/test/java/org/chenile/http/test/subclass/TestSubclassing.java

The controller method:

@PostMapping("/add-capacity")
@BodyTypeSelector("subclassBodyTypeSelector")
public ResponseEntity<GenericResponse<Capacity>> addCapacity(
        HttpServletRequest request,
        @ChenileParamType(Vehicle.class) @RequestBody String vehicle) {
    return process(request, vehicle);
}

The important pieces are:

  • controller receives a raw JSON string
  • @ChenileParamType(Vehicle.class) says the service contract should be treated as Vehicle
  • @BodyTypeSelector("subclassBodyTypeSelector") says a selector should refine that type

If the JSON body contains "type": "car", the selector upgrades the body type from Vehicle to Car. If it contains "type": "truck", it upgrades to Truck.

Then the transformers (by default JsonTransformer) deserialize into the chosen subclass, and the service method receives the correct object type.

Selector chaining

Chenile supports multiple body-type selectors in sequence.

Example from CapacityController:

@PostMapping("/add-capacity-generic/{type}")
@BodyTypeSelector({"roomVehicleBodyTypeSelector","subclassBodyTypeSelector"})
public ResponseEntity<GenericResponse<Capacity>> addCapacityGeneric(
        HttpServletRequest request,
        @PathVariable("type") String type,
        @ChenileParamType(Object.class) @RequestBody String object) {
    return process(request, type, object);
}

This is a two-stage selection strategy:

  1. roomVehicleBodyTypeSelector looks at header/path information and chooses a broad category like Room or Vehicle
  2. subclassBodyTypeSelector refines Vehicle into Car or Truck using the payload’s type field

That allows Chenile to express complex, context-sensitive transformation logic in a composable way.

Another custom selector example

The core tests also include a JSON-defined selector example:

  • chenile-core/src/test/resources/org/chenile/core/test/service/mockService.json
  • chenile-core/src/test/java/org/chenile/core/test/S6BodyTypeSelector.java

That example shows an operation whose body type is determined by event or request context rather than fixed at configuration time.

How transformation connects to service invocation

Transformation affects invocation directly because ServiceInvoker reads exchange.body when constructing method arguments.

The sequence is:

  1. TransformationClassSelector sets exchange.bodyType
  2. the configured transformers (by default JsonTransformer) convert exchange.body from its raw format to a typed object
  3. ServiceInvoker reads exchange.body
  4. the typed object is passed into the target Java method

So transformation is the bridge between transport-level input and method-level invocation.

Mental model

Use this model:

  • OperationDefinition.input is the default target type
  • body-type selectors can override that target type dynamically
  • exchange.bodyType is the effective deserialization target
  • the transformers in chenile.transformers convert the raw body into that type; JsonTransformer is the default
  • ServiceInvoker consumes the transformed object

Most relevant source files

  • chenile-core/src/main/java/org/chenile/core/transform/TransformationClassSelector.java
  • chenile-core/src/main/java/org/chenile/core/interceptors/interpolations/TransformersInterpolation.java
  • chenile-core/src/main/java/org/chenile/core/transform/JsonTransformer.java
  • chenile-core/src/main/java/org/chenile/core/model/ChenileConfiguration.java (getTransformers())
  • chenile-core/src/main/java/org/chenile/core/transform/SubclassRegistry.java
  • chenile-core/src/main/java/org/chenile/core/transform/SubclassBodyTypeSelector.java
  • chenile-core/src/main/java/org/chenile/http/annotation/BodyTypeSelector.java
  • chenile-core/src/main/java/org/chenile/core/init/OperationDefinitionProducerBase.java
  • chenile-core/src/main/java/org/chenile/core/init/AbstractServiceInitializer.java
  • chenile-http/src/test/java/org/chenile/http/test/controller/CapacityController.java
  • chenile-http/src/test/java/org/chenile/http/test/subclass/TestSubclassing.java
  • chenile-core/src/test/resources/org/chenile/core/test/service/mockService.json