davsclaus commented on code in PR #27792: URL: https://github.com/apache/camel/pull/27792#discussion_r4266928080
########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusEndpoint.java: ########## @@ -0,0 +1,405 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; +import org.citrusframework.exceptions.ValidationException; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.validation.context.ValidationContext; + +@UriEndpoint(firstVersion = "4.23.0", scheme = "citrus", title = "Citrus", syntax = "citrus:operation/name", Review Comment: 4.23.0 is already tagged and `camel-4.23.x` is branched, so this ships in 4.24.0. Please use `firstVersion = "4.24.0"` here, `<firstVersion>4.24.0</firstVersion>` in the pom, and `:since: 4.24` in `citrus-component.adoc`. Then regenerate the catalog JSON. ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusEndpoint.java: ########## @@ -0,0 +1,405 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; +import org.citrusframework.exceptions.ValidationException; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.validation.context.ValidationContext; + +@UriEndpoint(firstVersion = "4.23.0", scheme = "citrus", title = "Citrus", syntax = "citrus:operation/name", + producerOnly = true, remote = false, category = { Category.TESTING }) +public class CitrusEndpoint extends DefaultEndpoint { + + private final AtomicInteger exchangeIndex = new AtomicInteger(); + private final AtomicInteger receivedCount = new AtomicInteger(); + private final List<Exchange> receivedExchanges = new CopyOnWriteArrayList<>(); + private final List<Throwable> failures = new CopyOnWriteArrayList<>(); + + private volatile CountDownLatch latch; + + @UriPath(description = "The operation to perform. 'validate' validates exchanges without modifying them." + + " 'receive' validates exchanges and returns a simulated response.") + @Metadata(required = true) + private String operation; + + @UriPath(description = "A unique name to identify this endpoint. Allows multiple Citrus endpoints" + + " with different validation expectations in the same route.") + private String name; + + @UriParam(description = "The message type for validation. Determines which Citrus validation module is used." + + " Supported values: json, xml, yaml, plaintext.") + private String messageType; + + private MessageValidationSpec allMessagesSpec; + private final Map<Integer, MessageValidationSpec> indexedSpecs = new LinkedHashMap<>(); + private int nextSpecIndex; + + private MessageResponseSpec allMessagesResponseSpec; + private final Map<Integer, MessageResponseSpec> indexedResponseSpecs = new LinkedHashMap<>(); + private int nextResponseSpecIndex; + + private int expectedCount = -1; + + public CitrusEndpoint(String endpointUri, CitrusComponent component) { + super(endpointUri, component); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + throw new UnsupportedOperationException("You cannot consume from this endpoint"); + } + + @Override + public Producer createProducer() throws Exception { + return new CitrusProducer(this); + } + + // --- Fluent validation specification API (for 'validate' operation) --- + + public MessageValidationSpec allMessages() { + if (allMessagesSpec == null) { + allMessagesSpec = new MessageValidationSpec(); + } + return allMessagesSpec; + } + + public MessageValidationSpec message() { + return message(nextSpecIndex++); + } + + public MessageValidationSpec message(int index) { + return indexedSpecs.computeIfAbsent(index, k -> new MessageValidationSpec()); + } + + // --- Gherkin-style API (for 'receive' operation) --- + + public WhenSpec when() { + return new WhenSpec(); + } + + public ThenSpec then() { + return new ThenSpec(); + } + + public CitrusEndpoint expectedMessageCount(int count) { + this.expectedCount = count; + this.latch = new CountDownLatch(count); + return this; + } + + // --- Spec resolution --- + + int nextExchangeIndex() { + return exchangeIndex.getAndIncrement(); + } + + MessageValidationSpec resolveValidationSpec(int index) { + MessageValidationSpec indexed = indexedSpecs.get(index); + if (indexed != null) { + return indexed; + } + if (allMessagesSpec != null) { + return allMessagesSpec; + } + if (!indexedSpecs.isEmpty()) { + throw new IllegalStateException( + "No validation specification for exchange at index " + index + + " on endpoint: " + getEndpointUri() + + ". Validation specs are configured for indexes " + indexedSpecs.keySet() + + ". Use allMessages() to provide a default" + + " or message(" + index + ") for this specific exchange."); + } + return null; + } + + MessageResponseSpec resolveResponseSpec(int index) { + MessageResponseSpec indexed = indexedResponseSpecs.get(index); + if (indexed != null) { + return indexed; + } + return allMessagesResponseSpec; + } + + // --- Assertion API --- + + public void assertIsSatisfied() throws InterruptedException { + assertIsSatisfied(10, TimeUnit.SECONDS); + } + + public void assertIsSatisfied(long timeout, TimeUnit unit) throws InterruptedException { Review Comment: When `expectedMessageCount()` was never called, `latch` is null and `expectedCount` is -1, so this passes with zero exchanges received. For example, `citrus.message(0)...; citrus.message(1)...;` passes even if the route never reaches the endpoint. Could the expected count default to the number of indexed specs, or could this fail when specs exist and nothing arrived? ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusProducer.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageResponseSpec; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageValidationSpec; +import org.apache.camel.support.DefaultProducer; +import org.citrusframework.CitrusContext; +import org.citrusframework.context.TestContext; +import org.citrusframework.message.DefaultMessage; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.message.MessagePayloadUtils; +import org.citrusframework.message.MessageType; +import org.citrusframework.validation.MessageValidator; +import org.citrusframework.validation.MessageValidatorRegistry; +import org.citrusframework.validation.context.DefaultMessageValidationContext; +import org.citrusframework.validation.context.HeaderValidationContext; +import org.citrusframework.validation.context.ValidationContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitrusProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(CitrusProducer.class); + + private volatile CitrusContext citrusContext; + + public CitrusProducer(CitrusEndpoint endpoint) { + super(endpoint); + } + + @Override + public CitrusEndpoint getEndpoint() { + return (CitrusEndpoint) super.getEndpoint(); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + citrusContext = CitrusContext.create(); + } + + @Override + public void process(Exchange exchange) throws Exception { + CitrusEndpoint endpoint = getEndpoint(); + + try { + int index = endpoint.nextExchangeIndex(); + MessageValidationSpec spec = endpoint.resolveValidationSpec(index); + TestContext testContext = citrusContext.createTestContext(); + propagateExchangeProperties(exchange, testContext); + + if (spec != null) { + DefaultMessage receivedMessage = buildReceivedMessage(exchange); + DefaultMessage controlMessage = buildControlMessage(spec, testContext); + + String messageType = resolveMessageType(endpoint, spec); + controlMessage.setType(messageType); + + List<ValidationContext> validationContexts = buildValidationContexts(spec); + + performValidation(receivedMessage, controlMessage, testContext, validationContexts, messageType); + } + + if ("receive".equals(endpoint.getOperation())) { + MessageResponseSpec responseSpec = endpoint.resolveResponseSpec(index); + if (responseSpec != null) { + applyResponse(exchange, responseSpec, testContext); + } + } + } catch (Exception e) { + endpoint.addFailure(e); + throw e; + } finally { + endpoint.onExchangeReceived(exchange); + } + } + + private void propagateExchangeProperties(Exchange exchange, TestContext testContext) { Review Comment: Camel 4 exchange variables (`exchange.getVariables()`, the `setVariable` EIP) seem a closer match for Citrus test variables than exchange properties. Could both be propagated? The reverse direction is also a question: `@variable('x')@` in the docs extracts into this per-exchange `TestContext`, which is then discarded. Writing the extracted variables back as exchange variables would make the 'for later use' in the docs true. ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusEndpoint.java: ########## @@ -0,0 +1,405 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; +import org.citrusframework.exceptions.ValidationException; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.validation.context.ValidationContext; + +@UriEndpoint(firstVersion = "4.23.0", scheme = "citrus", title = "Citrus", syntax = "citrus:operation/name", + producerOnly = true, remote = false, category = { Category.TESTING }) +public class CitrusEndpoint extends DefaultEndpoint { Review Comment: Design question: `MockEndpoint.assertIsSatisfied(context)` and `MockEndpoint.resetMocks(context)` only handle `instanceof MockEndpoint`. So a `CamelTestSupport` test that uses the context-wide assert silently skips this endpoint. Did you consider `extends MockEndpoint`? You would get the context-wide assert and reset, and `expectedBodiesReceived`, `expectedHeaderReceived` and the other expectations, with Citrus validation added on top. The method names here (`expectedMessageCount`, `allMessages`, `message(int)`, `assertIsSatisfied`, `reset`) already follow `MockEndpoint`, but with different return types. Users may find that confusing. ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusProducer.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageResponseSpec; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageValidationSpec; +import org.apache.camel.support.DefaultProducer; +import org.citrusframework.CitrusContext; +import org.citrusframework.context.TestContext; +import org.citrusframework.message.DefaultMessage; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.message.MessagePayloadUtils; +import org.citrusframework.message.MessageType; +import org.citrusframework.validation.MessageValidator; +import org.citrusframework.validation.MessageValidatorRegistry; +import org.citrusframework.validation.context.DefaultMessageValidationContext; +import org.citrusframework.validation.context.HeaderValidationContext; +import org.citrusframework.validation.context.ValidationContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitrusProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(CitrusProducer.class); + + private volatile CitrusContext citrusContext; + + public CitrusProducer(CitrusEndpoint endpoint) { + super(endpoint); + } + + @Override + public CitrusEndpoint getEndpoint() { + return (CitrusEndpoint) super.getEndpoint(); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + citrusContext = CitrusContext.create(); + } + + @Override + public void process(Exchange exchange) throws Exception { + CitrusEndpoint endpoint = getEndpoint(); + + try { + int index = endpoint.nextExchangeIndex(); + MessageValidationSpec spec = endpoint.resolveValidationSpec(index); + TestContext testContext = citrusContext.createTestContext(); + propagateExchangeProperties(exchange, testContext); + + if (spec != null) { + DefaultMessage receivedMessage = buildReceivedMessage(exchange); + DefaultMessage controlMessage = buildControlMessage(spec, testContext); + + String messageType = resolveMessageType(endpoint, spec); + controlMessage.setType(messageType); + + List<ValidationContext> validationContexts = buildValidationContexts(spec); + + performValidation(receivedMessage, controlMessage, testContext, validationContexts, messageType); + } + + if ("receive".equals(endpoint.getOperation())) { + MessageResponseSpec responseSpec = endpoint.resolveResponseSpec(index); + if (responseSpec != null) { + applyResponse(exchange, responseSpec, testContext); + } + } + } catch (Exception e) { + endpoint.addFailure(e); + throw e; + } finally { + endpoint.onExchangeReceived(exchange); + } + } + + private void propagateExchangeProperties(Exchange exchange, TestContext testContext) { + Map<String, Object> properties = exchange.getProperties(); + for (Map.Entry<String, Object> entry : properties.entrySet()) { + if (entry.getValue() != null) { + testContext.setVariable(entry.getKey(), entry.getValue()); + } + } + } + + private DefaultMessage buildReceivedMessage(Exchange exchange) { + Object body = exchange.getIn().getBody(); + Map<String, Object> headers = new LinkedHashMap<>(exchange.getIn().getHeaders()); Review Comment: Camel header names are case-insensitive (`CaseInsensitiveMap`), but this copy into a `LinkedHashMap` loses that. So `header("content-type", ...)` will not match a `Content-Type` header, although Camel treats them as the same header. Citrus 5.0.2 has `new HeaderValidationContext.Builder().ignoreCase(true).build()`. Use that in `buildValidationContexts` instead of `new HeaderValidationContext()`. ########## components/camel-test/camel-test-citrus/pom.xml: ########## @@ -0,0 +1,119 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +--> +<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.camel</groupId> + <artifactId>camel-test-parent</artifactId> + <version>4.23.0-SNAPSHOT</version> + </parent> + + <artifactId>camel-test-citrus</artifactId> + <packaging>jar</packaging> + + <name>Camel :: Test :: Citrus</name> + <description>Citrus message validation component for testing</description> + + <properties> + <firstVersion>4.23.0</firstVersion> + <label>testing,java</label> + <title>Test Citrus</title> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-support</artifactId> + </dependency> + + <!-- Citrus core dependencies --> + <dependency> + <groupId>org.citrusframework</groupId> + <artifactId>citrus-api</artifactId> + <version>${citrus-version}</version> + </dependency> + <dependency> + <groupId>org.citrusframework</groupId> + <artifactId>citrus-base</artifactId> + <version>${citrus-version}</version> + </dependency> + + <!-- Test dependencies --> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-test-junit5</artifactId> Review Comment: New components use `camel-test-junit6`. Every component pom added in the last four months does. The explicit `junit-jupiter` dependency below is then redundant, and the `assertj-core` `<version>` can go, because `parent/pom.xml` already manages it. ########## components/camel-test/camel-test-citrus/src/test/java/org/apache/camel/component/citrus/CitrusValidateJsonTest.java: ########## @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import org.apache.camel.RoutesBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.test.junit5.CamelTestSupport; +import org.citrusframework.validation.DefaultValidations; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CitrusValidateJsonTest extends CamelTestSupport { + + @Test + void shouldValidateJsonBody() throws Exception { + CitrusEndpoint citrus = context.getEndpoint("citrus:validate?messageType=json", CitrusEndpoint.class); + citrus.allMessages().body(""" + { + "greeting": "Hello World!" + } + """); + citrus.expectedMessageCount(1); + + template.sendBody("direct:start", """ + { + "greeting": "Hello World!" + } + """); + + citrus.assertIsSatisfied(); + assertThat(citrus.getReceivedCount()).isEqualTo(1); + } + + @Test + void shouldFailOnJsonBodyMismatch() { + CitrusEndpoint citrus = context.getEndpoint("citrus:validate?messageType=json", CitrusEndpoint.class); + citrus.allMessages().body(""" + { + "greeting": "Hello World!" + } + """); + + assertThatThrownBy(() -> template.sendBody("direct:start", """ + { + "greeting": "Goodbye!" + } + """)) + .isInstanceOf(org.apache.camel.CamelExecutionException.class); Review Comment: This is a fully qualified class name. Import `CamelExecutionException` as the other test classes do (CLAUDE.md import style). ########## components/camel-test/camel-test-citrus/src/main/docs/citrus-component.adoc: ########## @@ -0,0 +1,378 @@ += Citrus Component +:doctitle: Citrus +:shortname: citrus +:artifactid: camel-test-citrus +:description: Citrus message validation component for testing +:since: 4.23 +:supportlevel: Preview +:tabs-sync-option: +:component-header: Only producer is supported + +*Since Camel {since}* + +*{component-header}* + +The Citrus component integrates with the https://citrusframework.org/[Citrus integration test framework] +to perform message validation on exchanges arriving at a Camel endpoint. It allows test authors to +verify exchange body content, headers, and path expressions (JsonPath, XPath) using Citrus validation +modules. + +This component is intended for use in Camel route unit and integration tests. + +== URI format + +---- +citrus:operation/name[?options] +---- + +Where `operation` is `validate` or `receive`, and `name` is an optional identifier to distinguish +multiple Citrus endpoints in the same route. + +* `validate` — validates exchanges without modifying them (pass-through validation). +* `receive` — validates exchanges and returns a simulated response (request/response simulation). + +// component options: START +include::partial$component-configure-options.adoc[] +include::partial$component-endpoint-options.adoc[] +include::partial$component-endpoint-headers.adoc[] +// component options: END + +== Usage + +The Citrus endpoint acts as a producer-only endpoint. Routes send exchanges *to* `citrus:validate`, +and the component validates each exchange using Citrus message validation. + +=== Validation modules + +The component does not bundle Citrus validation modules. You must add the required validation +module dependency for your message type to your test classpath: + +[cols="1,2", options="header"] +|=== +| Dependency | Description + +| `citrus-validation-json` +| JSON message validation with JsonPath expressions and JSON schema support + +| `citrus-validation-xml` +| XML message validation with XPath expressions, XML schema (XSD/WSDL) and XSLT support + +| `citrus-validation-text` +| Plain text message validation including binary (stream and base64) and gzip support + +| `citrus-validation-yaml` +| YAML message validation + +| `citrus-validation-binary` +| Binary message validation with stream comparison and base64 encoding + +| `citrus-validation-hamcrest` +| Hamcrest matcher assertions for use with JsonPath and XPath expressions +|=== + +All modules use the `org.citrusframework` group ID. Refer to the +https://citrusframework.org/citrus/reference/html/[Citrus reference documentation] for detailed +usage of each validation module. + +=== Citrus empowered message validation + +Citrus uses a powerful template-based approach to message validation: you provide an expected message template and +Citrus compares it against the received message using format-aware comparison. This brings several +capabilities beyond simple string equality. + +==== Ignore expressions + +Use the `@ignore@` placeholder anywhere in an expected message template to skip validation of dynamic +values such as timestamps, generated IDs, or correlation tokens. The element must be present, but its +value is not checked. + +[source,json] +---- +{ + "orderId": "@ignore@", + "timestamp": "@ignore@", + "status": "created" +} +---- + +This works across all supported message types — in XML element and attribute values, JSON property values, +and YAML property values. The ignore placeholder can also replace an entire sub-object or element +including its children. + +For plain text messages, the `@ignore@` placeholder works on a positional basis — it matches a word-length +character sequence at the exact position in the text. Use `@ignore(n)@` to ignore exactly _n_ characters +when the value contains non-word characters: + +[source,plaintext] +---- +Your current id is "@ignore@", it expires on 01/01/2030 +---- + +This ignores the word following `id is "` based on the position of the ignore expression in the template. +Because no character count is specified, Citrus ignores the entire word regardless of its length. +The word boundary is determined by the first non-word character (whitespace, punctuation, etc.). + +[source,plaintext] +---- +Your current id is "@ignore(12)@", it expires on @ignore(10)@ +---- + +This ignores the next 12 characters starting at the position of the ignore expression in the template. +This also includes whitespace and non-word characters (e.g. `Your current id is "1234/ 34567 D", it expires on 01/01/2030`). + +==== Validation matchers + +Citrus validation matchers are inline assertions embedded directly in the expected message template, +surrounded by `@` markers. They work across all message formats (JSON, XML, YAML, plain text) and +provide richer assertions than exact equality: + +[source,json] +---- +{ + "name": "@equalsIgnoreCase('JOHN')@", + "age": "@greaterThan(17)@", + "email": "@matches('[a-z]+@[a-z]+\\.[a-z]+')@", + "created": "@matchesDatePattern('yyyy-MM-dd')@", + "id": "@isNumber()@", + "token": "@startsWith('tk-')@", + "status": "@contains('active')@" +} +---- + +You can also use `@variable('name')@` to extract the actual value into a Citrus test variable for +later use, and `@assertThat(hamcrestMatcher)@` to use Hamcrest matchers inline (requires +`citrus-validation-hamcrest`): + +[source,json] +---- +{ + "count": "@assertThat(allOf(greaterThan(0), lessThan(100)))@", + "type": "@assertThat(anyOf(equalTo(A), equalTo(B)))@" +} +---- + +==== JSON validation + +Citrus JSON validation compares JSON object structures regardless of property order. +It supports two modes configurable via `citrus.json.message.validation.strict`: + +* **Strict mode** (default): the received JSON must match the expected structure exactly — no + additional properties or array items are allowed. +* **Non-strict mode**: the expected JSON can be a subset of the received message — additional + properties and array items in the received JSON are silently ignored. This is useful when you + only want to verify specific fields. + +JSON validation also supports: + +* **JsonPath expressions** for targeted field validation without specifying the full message body +* **JSON schema validation** against JSON Schema V3/V4 definitions +* **`@ignore@` and validation matchers** within JSON values + +==== XML validation + +Citrus XML validation performs a structural DOM tree comparison that correctly handles: + +* **XML namespaces** with different prefixes — the comparison is namespace-aware, so + `<ns1:element xmlns:ns1="...">` and `<ns2:element xmlns:ns2="...">` are treated as equivalent + when they share the same namespace URI. +* **XML schema validation** against XSD and WSDL definitions to verify structural correctness. +* **XPath expressions** for targeted element validation, with full namespace support via + namespace context configuration. This includes automatic namespace prefix resolution when the + prefixes differ between the control template and the received message. +* **`@ignore@` and validation matchers** within XML element values and attributes. + +==== Plain text validation + +Plain text validation performs exact string comparison with support for: + +* **Positional `@ignore@`** to skip dynamic word-length sequences at specific positions. +* **`@ignore(n)@`** to skip exactly _n_ characters (useful for values with non-word characters). +* **`@variable('name')@`** to extract values at specific positions into test variables. +* **Whitespace normalization** (configurable) to ignore line separator differences (CR, LF, CRLF) + or all whitespace. +* **Gzip** and **binary/base64** content comparison via the respective message types. + +==== YAML validation + +YAML validation compares YAML documents structurally, similar to JSON validation: + +* **Strict/non-strict mode** — configurable via `citrus.yaml.message.validation.strict`. +* **Path expressions** for ignoring specific elements in the YAML structure. +* **`@ignore@` and validation matchers** within YAML values. + +=== Validation specification API + +The endpoint provides a fluent API for specifying validation expectations. You can define a single +validation that applies to all incoming exchanges, or specify individual validations for each +exchange in sequence. + +==== Single validation for all exchanges + +Use `allMessages()` to define one validation specification that is applied to every exchange. +The returned `MessageValidationSpec` provides a fluent API with `body()`, `header()`, and +`validate()` methods: + +[source,java] +---- +CitrusEndpoint citrus = context.getEndpoint("citrus:validate?messageType=json", CitrusEndpoint.class); +citrus.allMessages() + .body("{\"status\": \"ok\"}") + .header("operation", "test"); +citrus.expectedMessageCount(3); + +// All three exchanges are validated against the same spec +template.sendBodyAndHeader("direct:start", "{\"status\": \"ok\"}", "operation", "test"); +template.sendBodyAndHeader("direct:start", "{\"status\": \"ok\"}", "operation", "test"); +template.sendBodyAndHeader("direct:start", "{\"status\": \"ok\"}", "operation", "test"); + +citrus.assertIsSatisfied(); +---- + +==== Per-exchange sequential validation + +Use `message()` to specify different validation expectations for the 1st, 2nd, 3rd, etc. +exchange. Each call to `message()` auto-increments the index, so specs are applied in order. +Each incoming exchange triggers the next validation spec in sequence: + +[source,java] +---- +CitrusEndpoint citrus = context.getEndpoint("citrus:validate?messageType=json", CitrusEndpoint.class); + +citrus.message().body("{\"event\": \"created\"}").header("action", "create"); +citrus.message().body("{\"event\": \"updated\"}").header("action", "update"); +citrus.message().body("{\"event\": \"deleted\"}").header("action", "delete"); +citrus.expectedMessageCount(3); + +template.sendBodyAndHeader("direct:start", "{\"event\": \"created\"}", "action", "create"); +template.sendBodyAndHeader("direct:start", "{\"event\": \"updated\"}", "action", "update"); +template.sendBodyAndHeader("direct:start", "{\"event\": \"deleted\"}", "action", "delete"); + +citrus.assertIsSatisfied(); +---- + +You can also use `message(index)` to target a specific exchange by its 0-based position. + +When both `message(index)` and `allMessages()` are configured, the indexed spec takes priority — +it replaces `allMessages()` for that exchange entirely (the two are never combined). The +`allMessages()` spec acts as a fallback for exchanges that have no matching indexed spec. + +If an exchange arrives at an index with no matching indexed spec and no `allMessages()` fallback, +the endpoint fails with an error. + +[source,java] +---- +citrus.message(0).body("{\"event\": \"start\"}"); +citrus.allMessages().body("{\"event\": \"progress\"}").header("type", "status"); + +// Exchange 0 → validated against message(0) only (allMessages() is NOT applied) +// Exchange 1, 2, ... → validated against allMessages() (body + header) +---- + +=== Receive operation (request/response simulation) + +The `receive` operation extends the validation endpoint with response simulation. It uses a +Gherkin-style fluent API to define what the endpoint expects to receive (`when`) and what it +should respond with (`then`). This is useful for simulating backend services in route tests. + +==== Basic usage + +[source,java] +---- +CitrusEndpoint citrus = context.getEndpoint("citrus:receive/service?messageType=json", CitrusEndpoint.class); + +// Define expected request and simulated response +citrus.when().allMessages().receive() + .body("{\"action\": \"greet\"}"); +citrus.then().allMessages().respond() + .body("{\"greeting\": \"Hello!\"}"); +citrus.expectedMessageCount(1); + +// Send a request and verify the response +Exchange result = template.send("direct:start", exchange -> { + exchange.getIn().setBody("{\"action\": \"greet\"}"); +}); + +citrus.assertIsSatisfied(); +assertThat(result.getIn().getBody(String.class)).isEqualTo("{\"greeting\": \"Hello!\"}"); +---- + +==== Gherkin-style API + +The `when()` and `then()` methods provide a natural-language-like syntax: + +* `when().message(index).receive()` — define validation expectations for a specific exchange +* `when().allMessages().receive()` — define default validation for all exchanges +* `then().message(index).respond()` — define the response for a specific exchange +* `then().allMessages().respond()` — define the default response for all exchanges +* `then().message(index).send()` — alias for `respond()` + +Both the `receive()` spec and the `respond()` spec support `body()` and `header()` methods. + +==== Per-exchange request/response + +You can define different request expectations and responses for each exchange in sequence: + +[source,java] +---- +CitrusEndpoint citrus = context.getEndpoint("citrus:receive/service?messageType=json", CitrusEndpoint.class); + +citrus.when().message(0).receive().body("{\"action\": \"create\"}"); +citrus.then().message(0).respond().body("{\"id\": \"1\", \"status\": \"created\"}"); + +citrus.when().message(1).receive().body("{\"action\": \"update\"}"); +citrus.then().message(1).respond().body("{\"id\": \"1\", \"status\": \"updated\"}"); + +citrus.expectedMessageCount(2); +---- + +Indexed specs take priority over `allMessages()` for both request validation and response +simulation. When a specific exchange has no indexed spec, the `allMessages()` spec is used as +a fallback. + +==== Response with headers + +[source,java] +---- +citrus.then().allMessages().respond() + .body("{\"greeting\": \"Hello!\"}") + .header("Content-Type", "application/json") + .header("X-Status", "ok"); +---- + +==== Citrus variables in responses + +Exchange properties are available as Citrus test variables in response templates. This enables +dynamic response generation based on the incoming request context: + +[source,java] +---- +citrus.then().allMessages().respond() + .body("{\"greeting\": \"Hello ${userName}!\"}") + .header("X-Correlation-Id", "${correlationId}"); +---- + +==== Response-only mode + +When you only need response simulation without request validation, omit the `when()` specification: + +[source,java] +---- +CitrusEndpoint citrus = context.getEndpoint("citrus:receive/responder", CitrusEndpoint.class); + +citrus.then().allMessages().respond() + .body("OK") + .header("status", "200"); +citrus.expectedMessageCount(1); +---- + +=== Exchange properties as Citrus variables + +All exchange properties are automatically propagated to the Citrus test context as test variables. +This enables the use of Citrus functions and validation matchers in expected message templates. + +=== Path validation Review Comment: This component does not classify `$` and `/` expressions. The user passes a validation context builder to `validate(...)`. The `validate(...)` API is not shown anywhere on this page. Suggest replacing this section with the examples from the tests: ```java citrus.allMessages().validate(new DefaultValidations().jsonPath() .expression("$.user.name", "John")); citrus.allMessages().validate(new DefaultValidations().xpath() .expression("/greeting/text", "Hello World!")); ``` ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusProducer.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageResponseSpec; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageValidationSpec; +import org.apache.camel.support.DefaultProducer; +import org.citrusframework.CitrusContext; +import org.citrusframework.context.TestContext; +import org.citrusframework.message.DefaultMessage; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.message.MessagePayloadUtils; +import org.citrusframework.message.MessageType; +import org.citrusframework.validation.MessageValidator; +import org.citrusframework.validation.MessageValidatorRegistry; +import org.citrusframework.validation.context.DefaultMessageValidationContext; +import org.citrusframework.validation.context.HeaderValidationContext; +import org.citrusframework.validation.context.ValidationContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitrusProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(CitrusProducer.class); + + private volatile CitrusContext citrusContext; + + public CitrusProducer(CitrusEndpoint endpoint) { + super(endpoint); + } + + @Override + public CitrusEndpoint getEndpoint() { + return (CitrusEndpoint) super.getEndpoint(); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + citrusContext = CitrusContext.create(); + } + + @Override + public void process(Exchange exchange) throws Exception { + CitrusEndpoint endpoint = getEndpoint(); + + try { + int index = endpoint.nextExchangeIndex(); + MessageValidationSpec spec = endpoint.resolveValidationSpec(index); + TestContext testContext = citrusContext.createTestContext(); + propagateExchangeProperties(exchange, testContext); + + if (spec != null) { + DefaultMessage receivedMessage = buildReceivedMessage(exchange); + DefaultMessage controlMessage = buildControlMessage(spec, testContext); + + String messageType = resolveMessageType(endpoint, spec); + controlMessage.setType(messageType); + + List<ValidationContext> validationContexts = buildValidationContexts(spec); + + performValidation(receivedMessage, controlMessage, testContext, validationContexts, messageType); + } + + if ("receive".equals(endpoint.getOperation())) { + MessageResponseSpec responseSpec = endpoint.resolveResponseSpec(index); + if (responseSpec != null) { + applyResponse(exchange, responseSpec, testContext); + } + } + } catch (Exception e) { + endpoint.addFailure(e); + throw e; Review Comment: Rethrowing puts the route's own error handling in charge of a test assertion: - `onException(...).handled(true)` or a dead letter channel swallows the failure. It is still recorded in `failures`, but the route takes a different path than in production. - With redelivery, `process()` runs again. That moves `exchangeIndex` and `receivedCount`, so `message(1)` is applied to the retry of the first exchange, and `expectedMessageCount` fails with a confusing count. `MockEndpoint` records failures and reports them in `assertIsSatisfied()`. For `validate`, I would do the same by default, perhaps with a fail-fast option. For `receive`, throwing makes sense. Either way, please add a test with a redelivery policy or an `onException`. ########## components/camel-test/camel-test-citrus/src/main/docs/citrus-component.adoc: ########## @@ -0,0 +1,378 @@ += Citrus Component +:doctitle: Citrus +:shortname: citrus +:artifactid: camel-test-citrus +:description: Citrus message validation component for testing +:since: 4.23 +:supportlevel: Preview +:tabs-sync-option: +:component-header: Only producer is supported + +*Since Camel {since}* + +*{component-header}* + +The Citrus component integrates with the https://citrusframework.org/[Citrus integration test framework] +to perform message validation on exchanges arriving at a Camel endpoint. It allows test authors to +verify exchange body content, headers, and path expressions (JsonPath, XPath) using Citrus validation +modules. + +This component is intended for use in Camel route unit and integration tests. + +== URI format + +---- +citrus:operation/name[?options] +---- + +Where `operation` is `validate` or `receive`, and `name` is an optional identifier to distinguish +multiple Citrus endpoints in the same route. + +* `validate` — validates exchanges without modifying them (pass-through validation). +* `receive` — validates exchanges and returns a simulated response (request/response simulation). + +// component options: START +include::partial$component-configure-options.adoc[] +include::partial$component-endpoint-options.adoc[] +include::partial$component-endpoint-headers.adoc[] +// component options: END + +== Usage + +The Citrus endpoint acts as a producer-only endpoint. Routes send exchanges *to* `citrus:validate`, +and the component validates each exchange using Citrus message validation. + +=== Validation modules + +The component does not bundle Citrus validation modules. You must add the required validation +module dependency for your message type to your test classpath: + +[cols="1,2", options="header"] +|=== +| Dependency | Description + +| `citrus-validation-json` +| JSON message validation with JsonPath expressions and JSON schema support + +| `citrus-validation-xml` +| XML message validation with XPath expressions, XML schema (XSD/WSDL) and XSLT support + +| `citrus-validation-text` +| Plain text message validation including binary (stream and base64) and gzip support + +| `citrus-validation-yaml` +| YAML message validation + +| `citrus-validation-binary` +| Binary message validation with stream comparison and base64 encoding + +| `citrus-validation-hamcrest` +| Hamcrest matcher assertions for use with JsonPath and XPath expressions +|=== + +All modules use the `org.citrusframework` group ID. Refer to the +https://citrusframework.org/citrus/reference/html/[Citrus reference documentation] for detailed +usage of each validation module. + +=== Citrus empowered message validation + +Citrus uses a powerful template-based approach to message validation: you provide an expected message template and +Citrus compares it against the received message using format-aware comparison. This brings several +capabilities beyond simple string equality. + +==== Ignore expressions + +Use the `@ignore@` placeholder anywhere in an expected message template to skip validation of dynamic +values such as timestamps, generated IDs, or correlation tokens. The element must be present, but its +value is not checked. + +[source,json] +---- +{ + "orderId": "@ignore@", + "timestamp": "@ignore@", + "status": "created" +} +---- + +This works across all supported message types — in XML element and attribute values, JSON property values, +and YAML property values. The ignore placeholder can also replace an entire sub-object or element +including its children. + +For plain text messages, the `@ignore@` placeholder works on a positional basis — it matches a word-length +character sequence at the exact position in the text. Use `@ignore(n)@` to ignore exactly _n_ characters +when the value contains non-word characters: + +[source,plaintext] +---- +Your current id is "@ignore@", it expires on 01/01/2030 +---- + +This ignores the word following `id is "` based on the position of the ignore expression in the template. +Because no character count is specified, Citrus ignores the entire word regardless of its length. +The word boundary is determined by the first non-word character (whitespace, punctuation, etc.). + +[source,plaintext] +---- +Your current id is "@ignore(12)@", it expires on @ignore(10)@ +---- + +This ignores the next 12 characters starting at the position of the ignore expression in the template. +This also includes whitespace and non-word characters (e.g. `Your current id is "1234/ 34567 D", it expires on 01/01/2030`). + +==== Validation matchers + +Citrus validation matchers are inline assertions embedded directly in the expected message template, +surrounded by `@` markers. They work across all message formats (JSON, XML, YAML, plain text) and +provide richer assertions than exact equality: + +[source,json] +---- +{ + "name": "@equalsIgnoreCase('JOHN')@", + "age": "@greaterThan(17)@", + "email": "@matches('[a-z]+@[a-z]+\\.[a-z]+')@", + "created": "@matchesDatePattern('yyyy-MM-dd')@", + "id": "@isNumber()@", + "token": "@startsWith('tk-')@", + "status": "@contains('active')@" +} +---- + +You can also use `@variable('name')@` to extract the actual value into a Citrus test variable for Review Comment: 'for later use': the `TestContext` is created per exchange and then discarded, so an extracted variable is only usable in the `receive` response of the same exchange. Please say that, or carry the variables over (see my comment on `propagateExchangeProperties`). ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusProducer.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageResponseSpec; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageValidationSpec; +import org.apache.camel.support.DefaultProducer; +import org.citrusframework.CitrusContext; +import org.citrusframework.context.TestContext; +import org.citrusframework.message.DefaultMessage; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.message.MessagePayloadUtils; +import org.citrusframework.message.MessageType; +import org.citrusframework.validation.MessageValidator; +import org.citrusframework.validation.MessageValidatorRegistry; +import org.citrusframework.validation.context.DefaultMessageValidationContext; +import org.citrusframework.validation.context.HeaderValidationContext; +import org.citrusframework.validation.context.ValidationContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitrusProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(CitrusProducer.class); + + private volatile CitrusContext citrusContext; + + public CitrusProducer(CitrusEndpoint endpoint) { + super(endpoint); + } + + @Override + public CitrusEndpoint getEndpoint() { + return (CitrusEndpoint) super.getEndpoint(); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + citrusContext = CitrusContext.create(); + } + + @Override + public void process(Exchange exchange) throws Exception { + CitrusEndpoint endpoint = getEndpoint(); + + try { + int index = endpoint.nextExchangeIndex(); + MessageValidationSpec spec = endpoint.resolveValidationSpec(index); + TestContext testContext = citrusContext.createTestContext(); + propagateExchangeProperties(exchange, testContext); + + if (spec != null) { + DefaultMessage receivedMessage = buildReceivedMessage(exchange); + DefaultMessage controlMessage = buildControlMessage(spec, testContext); + + String messageType = resolveMessageType(endpoint, spec); + controlMessage.setType(messageType); + + List<ValidationContext> validationContexts = buildValidationContexts(spec); + + performValidation(receivedMessage, controlMessage, testContext, validationContexts, messageType); + } + + if ("receive".equals(endpoint.getOperation())) { + MessageResponseSpec responseSpec = endpoint.resolveResponseSpec(index); + if (responseSpec != null) { + applyResponse(exchange, responseSpec, testContext); + } + } + } catch (Exception e) { + endpoint.addFailure(e); + throw e; + } finally { + endpoint.onExchangeReceived(exchange); + } + } + + private void propagateExchangeProperties(Exchange exchange, TestContext testContext) { + Map<String, Object> properties = exchange.getProperties(); + for (Map.Entry<String, Object> entry : properties.entrySet()) { + if (entry.getValue() != null) { + testContext.setVariable(entry.getKey(), entry.getValue()); + } + } + } + + private DefaultMessage buildReceivedMessage(Exchange exchange) { + Object body = exchange.getIn().getBody(); + Map<String, Object> headers = new LinkedHashMap<>(exchange.getIn().getHeaders()); + return new DefaultMessage(body, headers); + } + + private DefaultMessage buildControlMessage(MessageValidationSpec spec, TestContext testContext) { + DefaultMessage controlMessage; + Object resolvedBody = resolveBody(spec.getBody(), spec.getBodyBuilder(), testContext); + + if (resolvedBody != null) { + controlMessage = new DefaultMessage(resolvedBody); + } else { + controlMessage = new DefaultMessage(); + } + + Map<String, Object> expectedHeaders = spec.getHeaders(); + for (Map.Entry<String, Object> entry : expectedHeaders.entrySet()) { + Object value = entry.getValue(); + if (value instanceof String s) { + value = testContext.replaceDynamicContentInString(s); + } + controlMessage.setHeader(entry.getKey(), value); + } + + return controlMessage; + } + + private String resolveMessageType(CitrusEndpoint endpoint, MessageValidationSpec spec) { + String type = endpoint.getMessageType(); + if (type != null) { + if (MessageType.knows(type)) { + return MessageType.valueOf(type.toUpperCase()).name(); Review Comment: Minor: use `toUpperCase(Locale.ROOT)` here and on line 142. Under a Turkish default locale, `"binary".toUpperCase()` gives `BİNARY`. ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusProducer.java: ########## @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageResponseSpec; +import org.apache.camel.component.citrus.CitrusEndpoint.MessageValidationSpec; +import org.apache.camel.support.DefaultProducer; +import org.citrusframework.CitrusContext; +import org.citrusframework.context.TestContext; +import org.citrusframework.message.DefaultMessage; +import org.citrusframework.message.MessagePayloadBuilder; +import org.citrusframework.message.MessagePayloadUtils; +import org.citrusframework.message.MessageType; +import org.citrusframework.validation.MessageValidator; +import org.citrusframework.validation.MessageValidatorRegistry; +import org.citrusframework.validation.context.DefaultMessageValidationContext; +import org.citrusframework.validation.context.HeaderValidationContext; +import org.citrusframework.validation.context.ValidationContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CitrusProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(CitrusProducer.class); + + private volatile CitrusContext citrusContext; + + public CitrusProducer(CitrusEndpoint endpoint) { + super(endpoint); + } + + @Override + public CitrusEndpoint getEndpoint() { + return (CitrusEndpoint) super.getEndpoint(); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + citrusContext = CitrusContext.create(); + } + + @Override + public void process(Exchange exchange) throws Exception { + CitrusEndpoint endpoint = getEndpoint(); + + try { + int index = endpoint.nextExchangeIndex(); + MessageValidationSpec spec = endpoint.resolveValidationSpec(index); + TestContext testContext = citrusContext.createTestContext(); + propagateExchangeProperties(exchange, testContext); + + if (spec != null) { + DefaultMessage receivedMessage = buildReceivedMessage(exchange); + DefaultMessage controlMessage = buildControlMessage(spec, testContext); + + String messageType = resolveMessageType(endpoint, spec); + controlMessage.setType(messageType); + + List<ValidationContext> validationContexts = buildValidationContexts(spec); + + performValidation(receivedMessage, controlMessage, testContext, validationContexts, messageType); + } + + if ("receive".equals(endpoint.getOperation())) { + MessageResponseSpec responseSpec = endpoint.resolveResponseSpec(index); + if (responseSpec != null) { + applyResponse(exchange, responseSpec, testContext); + } + } + } catch (Exception e) { + endpoint.addFailure(e); + throw e; + } finally { + endpoint.onExchangeReceived(exchange); + } + } + + private void propagateExchangeProperties(Exchange exchange, TestContext testContext) { + Map<String, Object> properties = exchange.getProperties(); + for (Map.Entry<String, Object> entry : properties.entrySet()) { + if (entry.getValue() != null) { + testContext.setVariable(entry.getKey(), entry.getValue()); + } + } + } + + private DefaultMessage buildReceivedMessage(Exchange exchange) { + Object body = exchange.getIn().getBody(); Review Comment: This passes the raw body to Citrus. For an `InputStream` or `StreamCache` body (for example from platform-http or file), Citrus' `DefaultTypeConverter` reads the stream and nothing resets it. So the next step in the route may see an empty body. That contradicts the docs, which say `validate` does not modify the exchange. POJO or `Map` bodies (for example after `unmarshal().json()`) go through Citrus' converter, not Camel's. Suggest converting text-based message types with Camel's type converter, calling `MessageHelper.resetStreamCache(exchange.getIn())` after validation, and adding a test with an `InputStream` body followed by a step that reads it. ########## components/camel-test/camel-test-citrus/src/main/java/org/apache/camel/component/citrus/CitrusComponent.java: ########## @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.citrus; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.DefaultComponent; + +@Component("citrus") +public class CitrusComponent extends DefaultComponent { Review Comment: Could the component own the `CitrusContext`? Create it in `doStart`, close it in `doStop`, and share it across endpoints, rather than one per producer. Also allow an existing `CitrusContext` from the registry, as an autowired component option. A test that runs under the Citrus JUnit extension could then share its context and variables with the route. This would also fix the leak gnodet-bot reported on the producer. ########## components/camel-test/camel-test-citrus/src/main/docs/citrus-component.adoc: ########## @@ -0,0 +1,378 @@ += Citrus Component +:doctitle: Citrus +:shortname: citrus +:artifactid: camel-test-citrus +:description: Citrus message validation component for testing +:since: 4.23 +:supportlevel: Preview +:tabs-sync-option: +:component-header: Only producer is supported + +*Since Camel {since}* + +*{component-header}* + +The Citrus component integrates with the https://citrusframework.org/[Citrus integration test framework] +to perform message validation on exchanges arriving at a Camel endpoint. It allows test authors to +verify exchange body content, headers, and path expressions (JsonPath, XPath) using Citrus validation +modules. + +This component is intended for use in Camel route unit and integration tests. + +== URI format + +---- +citrus:operation/name[?options] +---- + +Where `operation` is `validate` or `receive`, and `name` is an optional identifier to distinguish +multiple Citrus endpoints in the same route. + +* `validate` — validates exchanges without modifying them (pass-through validation). +* `receive` — validates exchanges and returns a simulated response (request/response simulation). + +// component options: START +include::partial$component-configure-options.adoc[] +include::partial$component-endpoint-options.adoc[] +include::partial$component-endpoint-headers.adoc[] +// component options: END + +== Usage Review Comment: Please add the usual 'Maven users will need to add the following dependency' block before this section, with `<scope>test</scope>`. The artifactId (`camel-test-citrus`) differs from the scheme (`citrus`), so users cannot guess it. A short full example with `CamelTestSupport` would also help. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
