ExtractField.java
Overview
`ExtractField.java` defines the `ExtractField` class, a Camel `Processor` implementation designed to extract a specific field from a JSON message body within an Apache Camel Exchange during Kafka message processing. The extracted value can either replace the message body or be stored in a message header, based on configurable options.
This processor is typically used in Kafka integration pipelines to isolate and promote a particular JSON field from the message payload, facilitating downstream routing, filtering, or processing logic that depends on that field.
Class: ExtractField
public class ExtractField implements Processor
Purpose
Extract a single field's value from the JSON message body.
Optionally place the extracted value into a configurable message header instead of replacing the body.
Optionally enforce strict checks to avoid overwriting existing headers.
Optionally set a property indicating whether the field was trimmed.
Key Features
Works with JSON payloads parsed into Jackson
JsonNode.Uses Jackson's
ObjectMapperto convert JSON nodes to a genericMapfor flexible field extraction.Supports configurable output modes: body replacement or header insertion.
Supports strict header existence checks to prevent overwriting.
Supports trimming flag to signal downstream processors.
Fields
Field Name | Type | Description |
|---|---|---|
`String field` | String | The name of the JSON field to extract from the message body. |
`String headerOutputName` | String | Optional header name to place the extracted field value into. Defaults to a constant header if unset. |
`boolean headerOutput` | boolean | Flag to output extracted field value in a header instead of the message body. |
`boolean strictHeaderCheck` | boolean | When `true`, only extract to header if the header does not already exist (avoids overwrite). |
`boolean trimField` | boolean | When `true`, sets a Camel exchange property `"trimField"` to `"true"`, else `"false"`. |
Constants
Constant Name | Type | Value | Description |
|---|---|---|---|
`EXTRACTED_FIELD_HEADER` | String | `"CamelKameletsExtractFieldName"` | Default header name used for extracted fields if none specified. |
Constructors
ExtractField()
Default no-argument constructor.
Initializes an instance with default settings; the
fieldmust be set via setter before processing.
ExtractField(String field)
Parameterized constructor.
Sets the field name to extract upon instantiation.
**Example:**
ExtractField extractor = new ExtractField("userId");
Methods
void process(Exchange ex) throws InvalidPayloadException
Processes the incoming Camel
Exchange.Extracts the configured
fieldfrom the JSON body.Depending on configuration, either replaces the message body with the extracted value or sets it as a header.
Throws
InvalidPayloadExceptionif the message body is not valid JSON (JsonNode).Sets the
"trimField"property based on thetrimFieldflag.
**Parameters:**
Parameter | Type | Description |
|---|---|---|
`ex` | Exchange | The Camel exchange object for the current message. |
**Throws:**
InvalidPayloadExceptionif body cannot be coerced toJsonNode.
**Usage example:**
ExtractField extractor = new ExtractField("orderId");
extractor.setHeaderOutput(true);
extractor.setHeaderOutputName("ExtractedOrderId");
extractor.process(exchange);
void setField(String field)
Setter for the field name to extract.
void setHeaderOutput(boolean headerOutput)
Setter for
headerOutputflag.If
true, extracted value is stored in a header instead of replacing the body.
void setHeaderOutputName(String headerOutputName)
Setter for the custom header name to use when
headerOutputis enabled.If not set or set to
"none", defaults toEXTRACTED_FIELD_HEADER.
void setStrictHeaderCheck(boolean strictHeaderCheck)
Setter for
strictHeaderCheck.When
true, the processor will check if the specified header exists before setting it, avoiding overwriting.
void setTrimField(boolean trimField)
Setter for
trimField.Controls whether a property
"trimField"is set on the exchange to"true"or"false"after extraction.
Private Helper Methods
private void extractToHeader(Exchange ex, Map<Object, Object> body)
Handles placing the extracted field value into the appropriate header.
Uses either the configured
headerOutputNameor defaults toEXTRACTED_FIELD_HEADER.Called from
process()whenheaderOutputis enabled.
private boolean checkHeaderExistence(Exchange exchange)
Checks if the target header (either
headerOutputNameor default) already exists.Used to enforce
strictHeaderChecklogic, preventing header overwrite.
Implementation Details and Algorithm
Parsing JSON Body:
The processor attempts to retrieve the message body as a Jackson
JsonNode.If the body is not a valid JSON node, throws
InvalidPayloadException.
Conversion to Map:
Converts the
JsonNodeinto a genericMap<Object, Object>using Jackson'sObjectMapperandTypeReference.This facilitates easy field extraction with dynamic key lookup.
Extraction Logic:
If
headerOutputisfalse, orstrictHeaderCheckistruebut the target header already exists, it replaces the message body with the extracted value.Otherwise, it extracts the field value into the specified header.
Setting Properties:
Sets the exchange property
"trimField"to"true"or"false"depending on thetrimFieldflag.This allows downstream processors or routes to react accordingly.
Usage Example
// Create processor to extract "customerId" from JSON body
ExtractField extractor = new ExtractField("customerId");
// Configure to output extracted value into a header named "Customer-ID"
extractor.setHeaderOutput(true);
extractor.setHeaderOutputName("Customer-ID");
// Enable strict check to avoid overwriting existing headers
extractor.setStrictHeaderCheck(true);
// Enable trim field property setting
extractor.setTrimField(true);
// In a Camel route:
// .process(extractor)
This will extract the value of the `"customerId"` field from the JSON body. If the `"Customer-ID"` header does not already exist, it will be set with this value. Additionally, the property `"trimField"` will be set to `"true"` on the exchange.
Interaction with Other System Components
Apache Camel Exchange:
The processor operates on the Camel
Exchangeobject, reading the incoming JSON message body and modifying the message body or headers.Kafka Message Processing:
Typically used in Kafka integration routes where JSON payloads are processed. Extracted fields can be promoted to headers used for routing or filtering Kafka messages downstream.
Jackson Library:
Uses Jackson's
ObjectMapperandJsonNodefor JSON parsing and conversion, enabling flexible JSON tree traversal and field extraction.Other Processors:
Can be combined with other JSON field manipulation processors (e.g.,
InsertField,DropField) or routing processors (e.g.,RegexRouter) to implement complex transformation and routing logic.
Mermaid Class Diagram
classDiagram
class ExtractField {
-String field
-String headerOutputName
-boolean headerOutput
-boolean strictHeaderCheck
-boolean trimField
+void process(Exchange ex) throws InvalidPayloadException
+void setField(String field)
+void setHeaderOutput(boolean headerOutput)
+void setHeaderOutputName(String headerOutputName)
+void setStrictHeaderCheck(boolean strictHeaderCheck)
+void setTrimField(boolean trimField)
-void extractToHeader(Exchange ex, Map<Object,Object> body)
-boolean checkHeaderExistence(Exchange exchange)
}
Summary
The `ExtractField` processor facilitates efficient and configurable extraction of specific JSON fields from Kafka messages within Apache Camel routes. By supporting both body replacement and header insertion modes, along with strict header existence checks and trimming flags, it enables flexible integration patterns and enhances message enrichment and routing capabilities in Kafka-based data pipelines.
This class is a key component in the suite of JSON field manipulation processors that allow fine-grained control over Kafka message contents and metadata, ensuring streamlined and maintainable transformations in complex integration scenarios.