This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 7870cd4edb53 CAMEL-25651: fix YAML route dump dropping top-level
errorHandler, intercept and onCompletion (#30268)
7870cd4edb53 is described below
commit 7870cd4edb5316c86cd0b28082ee244d01d4c2b7
Author: Guillaume Nodet <[email protected]>
AuthorDate: Sat Nov 21 08:03:11 2026 +0100
CAMEL-25651: fix YAML route dump dropping top-level errorHandler, intercept
and onCompletion (#30268)
The YAML route dump now writes the context-scoped errorHandler, intercept,
interceptFrom, interceptSendToEndpoint and onCompletion as top-level entries
before the routes, once for all routes, so a dump read back gives the same
routes. The constructs of a named route configuration stay out of the
top-level entries. RouteDefinitionHelper.initInterceptors marks the
context-scoped intercepts (an identity set of the ones passed in) for the
dumper, and the order of the intercepts at runtime is unchanged.
---
.../apache/camel/model/InterceptDefinition.java | 13 +
.../model/InterceptSendToEndpointDefinition.java | 13 +
.../org/apache/camel/model/RouteDefinition.java | 38 ++
.../apache/camel/model/RouteDefinitionHelper.java | 50 ++-
.../org/apache/camel/yaml/LwModelToYAMLDumper.java | 219 +++++++++++-
.../yaml/ContextScopedTopLevelYamlDumpTest.java | 387 +++++++++++++++++++++
6 files changed, 706 insertions(+), 14 deletions(-)
diff --git
a/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptDefinition.java
b/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptDefinition.java
index dec75804ec2f..cb70020e025b 100644
---
a/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptDefinition.java
+++
b/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptDefinition.java
@@ -23,6 +23,7 @@ import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlTransient;
import org.apache.camel.Predicate;
import org.apache.camel.spi.AsPredicate;
@@ -37,6 +38,9 @@ import org.apache.camel.spi.Metadata;
@XmlAccessorType(XmlAccessType.FIELD)
public class InterceptDefinition extends OutputDefinition<InterceptDefinition>
{
+ @XmlTransient
+ private boolean routeScoped = true;
+
@Metadata(description = "To use an expression to only trigger intercepting
in specific situations")
@XmlElement
@AsPredicate
@@ -47,6 +51,7 @@ public class InterceptDefinition extends
OutputDefinition<InterceptDefinition> {
protected InterceptDefinition(InterceptDefinition source) {
super(source);
+ this.routeScoped = source.routeScoped;
this.onWhen = source.onWhen != null ? source.onWhen.copyDefinition() :
null;
}
@@ -55,6 +60,14 @@ public class InterceptDefinition extends
OutputDefinition<InterceptDefinition> {
return new InterceptDefinition(this);
}
+ public boolean isRouteScoped() {
+ return routeScoped;
+ }
+
+ public void setRouteScoped(boolean routeScoped) {
+ this.routeScoped = routeScoped;
+ }
+
@Override
public String toString() {
return "Intercept[" + getOutputs() + "]";
diff --git
a/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java
b/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java
index 0d2c9b8d3b6f..9f581dde710a 100644
---
a/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java
+++
b/core/camel-core-model/src/main/java/org/apache/camel/model/InterceptSendToEndpointDefinition.java
@@ -24,6 +24,7 @@ import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlTransient;
import org.apache.camel.Predicate;
import org.apache.camel.spi.AsPredicate;
@@ -39,6 +40,9 @@ import org.apache.camel.spi.annotations.DslArg;
@XmlAccessorType(XmlAccessType.FIELD)
public class InterceptSendToEndpointDefinition extends
OutputDefinition<InterceptSendToEndpointDefinition> {
+ @XmlTransient
+ private boolean routeScoped = true;
+
@XmlAttribute(required = true)
@DslArg
@Metadata(description = "Intercept sending to the uri or uri pattern.")
@@ -61,6 +65,7 @@ public class InterceptSendToEndpointDefinition extends
OutputDefinition<Intercep
protected
InterceptSendToEndpointDefinition(InterceptSendToEndpointDefinition source) {
super(source);
+ this.routeScoped = source.routeScoped;
this.uri = source.uri;
this.skipSendToOriginalEndpoint = source.skipSendToOriginalEndpoint;
this.afterUri = source.afterUri;
@@ -76,6 +81,14 @@ public class InterceptSendToEndpointDefinition extends
OutputDefinition<Intercep
return new InterceptSendToEndpointDefinition(this);
}
+ public boolean isRouteScoped() {
+ return routeScoped;
+ }
+
+ public void setRouteScoped(boolean routeScoped) {
+ this.routeScoped = routeScoped;
+ }
+
@Override
public List<ProcessorDefinition<?>> getOutputs() {
return outputs;
diff --git
a/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinition.java
b/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinition.java
index 3bdd950dd2b1..419da5c4c8fc 100644
---
a/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinition.java
+++
b/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinition.java
@@ -66,6 +66,8 @@ public class RouteDefinition extends
OutputDefinition<RouteDefinition>
private FromDefinition input;
private String routeConfigurationId;
private transient Set<String> appliedRouteConfigurationIds;
+ private transient List<InterceptDefinition> contextScopedIntercepts;
+ private transient List<OnCompletionDefinition> contextScopedOnCompletions;
private String group;
private String nodePrefixId;
private String streamCache;
@@ -161,6 +163,8 @@ public class RouteDefinition extends
OutputDefinition<RouteDefinition>
*/
public void resetPrepare() {
appliedRouteConfigurationIds = null;
+ contextScopedIntercepts = null;
+ contextScopedOnCompletions = null;
}
@Override
@@ -1011,6 +1015,40 @@ public class RouteDefinition extends
OutputDefinition<RouteDefinition>
return appliedRouteConfigurationIds;
}
+ /**
+ * Returns the context-scoped (global) intercepts that were injected into
this route when it was prepared. Unlike
+ * route-scoped intercepts, context-scoped intercepts are shared across
all routes; this list is used by the YAML
+ * dumper to emit them as top-level entries, since {@code
InterceptReifier} removes them from route outputs during
+ * {@code context.start()}.
+ */
+ public List<InterceptDefinition> getContextScopedIntercepts() {
+ return contextScopedIntercepts;
+ }
+
+ public void addContextScopedIntercept(InterceptDefinition intercept) {
+ if (contextScopedIntercepts == null) {
+ contextScopedIntercepts = new ArrayList<>();
+ }
+ contextScopedIntercepts.add(intercept);
+ }
+
+ /**
+ * Returns the context-scoped (global) onCompletions that were injected
into this route when it was prepared. This
+ * list is used by the YAML dumper to emit them as top-level entries
without touching the runtime
+ * {@code routeScoped} flag on {@link OnCompletionDefinition}, which
already has runtime semantics in
+ * {@code OnCompletionProcessor.shouldSkip()}.
+ */
+ public List<OnCompletionDefinition> getContextScopedOnCompletions() {
+ return contextScopedOnCompletions;
+ }
+
+ public void addContextScopedOnCompletion(OnCompletionDefinition
onCompletion) {
+ if (contextScopedOnCompletions == null) {
+ contextScopedOnCompletions = new ArrayList<>();
+ }
+ contextScopedOnCompletions.add(onCompletion);
+ }
+
public String getGroup() {
return group;
}
diff --git
a/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinitionHelper.java
b/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinitionHelper.java
index dd2f2151e433..1ed98e5bf589 100644
---
a/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinitionHelper.java
+++
b/core/camel-core-model/src/main/java/org/apache/camel/model/RouteDefinitionHelper.java
@@ -19,7 +19,9 @@ package org.apache.camel.model;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
+import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -449,7 +451,7 @@ public final class RouteDefinitionHelper {
initInterceptors(context, route, abstracts, upper, intercepts,
interceptFromDefinitions,
interceptSendToEndpointDefinitions);
// then on completion
- initOnCompletions(abstracts, upper, onCompletions);
+ initOnCompletions(route, abstracts, upper, onCompletions);
// then sagas
initSagas(abstracts, lower);
// then transactions
@@ -604,7 +606,21 @@ public final class RouteDefinitionHelper {
List<InterceptDefinition> intercepts,
List<InterceptFromDefinition> interceptFromDefinitions,
List<InterceptSendToEndpointDefinition>
interceptSendToEndpointDefinitions) {
- // move the abstracts interceptors into the dedicated list
+ // Build an identity set of the passed-in (context-scoped) intercepts
before merging the route's own abstracts.
+ // Using identity (not equals) avoids false positives when two
definitions are structurally equal.
+ Set<Object> contextScoped = Collections.newSetFromMap(new
IdentityHashMap<>());
+ if (intercepts != null) {
+ contextScoped.addAll(intercepts);
+ }
+ if (interceptFromDefinitions != null) {
+ contextScoped.addAll(interceptFromDefinitions);
+ }
+ if (interceptSendToEndpointDefinitions != null) {
+ contextScoped.addAll(interceptSendToEndpointDefinitions);
+ }
+
+ // Merge the route's own inline intercepts (from abstracts) into the
shared lists — same as before the fix,
+ // preserving the original single-pass insertion order.
for (ProcessorDefinition processor : abstracts) {
if (processor instanceof InterceptSendToEndpointDefinition
interceptSendToEndpointDefinition) {
if (interceptSendToEndpointDefinitions == null) {
@@ -624,18 +640,27 @@ public final class RouteDefinitionHelper {
}
}
- doInitInterceptors(context, route, upper, intercepts,
interceptFromDefinitions, interceptSendToEndpointDefinitions);
+ doInitInterceptors(context, route, upper, intercepts,
interceptFromDefinitions,
+ interceptSendToEndpointDefinitions, contextScoped);
}
private static void doInitInterceptors(
CamelContext context, RouteDefinition route,
List<ProcessorDefinition<?>> upper,
List<InterceptDefinition> intercepts,
List<InterceptFromDefinition> interceptFromDefinitions,
- List<InterceptSendToEndpointDefinition>
interceptSendToEndpointDefinitions) {
+ List<InterceptSendToEndpointDefinition>
interceptSendToEndpointDefinitions,
+ Set<Object> contextScoped) {
// configure intercept
if (intercepts != null && !intercepts.isEmpty()) {
for (InterceptDefinition intercept : intercepts) {
+ if (contextScoped.contains(intercept)) {
+ // mark as context-scoped so the YAML dumper can
distinguish them from route-scoped intercepts
+ intercept.setRouteScoped(false);
+ // keep a persistent reference on the route definition —
InterceptReifier will remove the intercept
+ // from route.getOutputs() during context.start(), so the
YAML dumper needs another way to find it
+ route.addContextScopedIntercept(intercept);
+ }
// init the parent
initParent(intercept);
// add as first output so intercept is handled before the
actual
@@ -700,6 +725,10 @@ public final class RouteDefinitionHelper {
}
if (match) {
+ if (contextScoped.contains(intercept)) {
+ // mark as context-scoped so the YAML dumper can
distinguish them from route-scoped intercepts
+ intercept.setRouteScoped(false);
+ }
// init the parent
initParent(intercept);
// add as first output so intercept is handled before the
@@ -715,6 +744,10 @@ public final class RouteDefinitionHelper {
if (interceptSendToEndpointDefinitions != null &&
!interceptSendToEndpointDefinitions.isEmpty()) {
for (InterceptSendToEndpointDefinition intercept :
interceptSendToEndpointDefinitions) {
intercept.afterPropertiesSet();
+ if (contextScoped.contains(intercept)) {
+ // mark as context-scoped so the YAML dumper can
distinguish them from route-scoped intercepts
+ intercept.setRouteScoped(false);
+ }
// init the parent
initParent(intercept);
// add as first output so intercept is handled before the
actual
@@ -727,7 +760,7 @@ public final class RouteDefinitionHelper {
}
private static void initOnCompletions(
- List<ProcessorDefinition<?>> abstracts,
List<ProcessorDefinition<?>> upper,
+ RouteDefinition route, List<ProcessorDefinition<?>> abstracts,
List<ProcessorDefinition<?>> upper,
List<OnCompletionDefinition> onCompletions) {
List<OnCompletionDefinition> completions = new ArrayList<>();
@@ -741,8 +774,13 @@ public final class RouteDefinitionHelper {
// only add global onCompletion if there are no route already
if (completions.isEmpty() && onCompletions != null) {
completions = onCompletions;
- // init the parent
+ // init the parent and record as context-scoped for the YAML dumper
+ // NOTE: do NOT call setRouteScoped(false) here — routeScoped
already drives runtime behaviour in
+ // OnCompletionProcessor.shouldSkip() and OnCompletionReifier
per-configuration dedup. Named route
+ // configurations intentionally keep routeScoped=true (see
CAMEL-25135). Instead, track them on the
+ // route via a separate transient list that the YAML dumper can
read without touching the runtime flag.
for (OnCompletionDefinition global : completions) {
+ route.addContextScopedOnCompletion(global);
initParent(global);
}
}
diff --git
a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java
b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java
index 6d6a6441be5e..0d6158b81cf5 100644
---
a/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java
+++
b/core/camel-yaml-io/src/main/java/org/apache/camel/yaml/LwModelToYAMLDumper.java
@@ -29,17 +29,21 @@ import java.util.function.Function;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
+import org.apache.camel.ErrorHandlerFactory;
import org.apache.camel.Expression;
import org.apache.camel.NamedNode;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.model.BeanFactoryDefinition;
import org.apache.camel.model.DataFormatDefinition;
+import org.apache.camel.model.ErrorHandlerDefinition;
import org.apache.camel.model.ExpressionNode;
import org.apache.camel.model.FromDefinition;
+import org.apache.camel.model.InterceptDefinition;
import org.apache.camel.model.InterceptFromDefinition;
import org.apache.camel.model.InterceptSendToEndpointDefinition;
import org.apache.camel.model.Model;
+import org.apache.camel.model.OnCompletionDefinition;
import org.apache.camel.model.OnExceptionDefinition;
import org.apache.camel.model.OptionalIdentifiedDefinition;
import org.apache.camel.model.RouteConfigurationDefinition;
@@ -53,6 +57,9 @@ import org.apache.camel.model.SwitchDefinition;
import org.apache.camel.model.ThrowExceptionDefinition;
import org.apache.camel.model.ToDynamicDefinition;
import org.apache.camel.model.dataformat.DataFormatsDefinition;
+import org.apache.camel.model.errorhandler.DefaultErrorHandlerDefinition;
+import org.apache.camel.model.errorhandler.NoErrorHandlerDefinition;
+import org.apache.camel.model.errorhandler.RefErrorHandlerDefinition;
import org.apache.camel.model.language.ExpressionDefinition;
import org.apache.camel.model.rest.RestDefinition;
import org.apache.camel.model.rest.RestsDefinition;
@@ -114,22 +121,63 @@ public class LwModelToYAMLDumper implements
ModelToYAMLDumper {
// context scoped onExceptions (a top-level onException in the YAML
DSL, an onException in the configure method
// of a RouteBuilder, or one of a route configuration) are added to
the outputs of each route when the routes
// are prepared, but the YAML DSL does not allow them in the steps of
a route
- List<OnExceptionDefinition> contextScoped = new ArrayList<>();
+ List<OnExceptionDefinition> contextScopedOnExceptions = new
ArrayList<>();
+ // context scoped intercepts (intercept, interceptFrom,
interceptSendToEndpoint) and onCompletions are also
+ // added to the outputs of each route when the routes are prepared
+ List<InterceptDefinition> contextScopedIntercepts = new ArrayList<>();
+ List<InterceptFromDefinition> contextScopedInterceptFroms = new
ArrayList<>();
+ List<InterceptSendToEndpointDefinition> contextScopedInterceptSendTos
= new ArrayList<>();
+ List<OnCompletionDefinition> contextScopedOnCompletions = new
ArrayList<>();
if (definition instanceof RoutesDefinition routes) {
- routes.getRoutes().forEach(route ->
collectContextScopedOnExceptions(route, contextScoped));
+ routes.getRoutes().forEach(route -> {
+ collectContextScopedOnExceptions(route,
contextScopedOnExceptions);
+ collectContextScopedIntercepts(route, contextScopedIntercepts);
+ collectContextScopedInterceptFroms(route,
contextScopedInterceptFroms);
+ collectContextScopedInterceptSendTos(route,
contextScopedInterceptSendTos);
+ collectContextScopedOnCompletions(route,
contextScopedOnCompletions);
+ });
} else if (definition instanceof RouteDefinition route) {
- collectContextScopedOnExceptions(route, contextScoped);
+ collectContextScopedOnExceptions(route, contextScopedOnExceptions);
+ collectContextScopedIntercepts(route, contextScopedIntercepts);
+ collectContextScopedInterceptFroms(route,
contextScopedInterceptFroms);
+ collectContextScopedInterceptSendTos(route,
contextScopedInterceptSendTos);
+ collectContextScopedOnCompletions(route,
contextScopedOnCompletions);
}
// the onExceptions of a route configuration are dumped with the route
configuration, the others are dumped
// once, as top-level onExceptions before the routes
- List<OnExceptionDefinition> topLevel = new ArrayList<>(contextScoped);
- topLevel.removeIf(oe -> isInRouteConfiguration(context, oe));
+ List<OnExceptionDefinition> topLevelOnExceptions = new
ArrayList<>(contextScopedOnExceptions);
+ topLevelOnExceptions.removeIf(oe -> isInRouteConfiguration(context,
oe));
+
+ // similarly, filter out constructs that belong to a route
configuration (they are dumped with the config)
+ List<InterceptDefinition> topLevelIntercepts = new
ArrayList<>(contextScopedIntercepts);
+ topLevelIntercepts.removeIf(i ->
isInterceptInRouteConfiguration(context, i));
+ List<InterceptFromDefinition> topLevelInterceptFroms = new
ArrayList<>(contextScopedInterceptFroms);
+ topLevelInterceptFroms.removeIf(i ->
isInterceptFromInRouteConfiguration(context, i));
+ List<InterceptSendToEndpointDefinition> topLevelInterceptSendTos = new
ArrayList<>(contextScopedInterceptSendTos);
+ topLevelInterceptSendTos.removeIf(i ->
isInterceptSendToInRouteConfiguration(context, i));
+ List<OnCompletionDefinition> topLevelOnCompletions = new
ArrayList<>(contextScopedOnCompletions);
+ topLevelOnCompletions.removeIf(oc ->
isOnCompletionInRouteConfiguration(context, oc));
+
+ // all context-scoped outputs to suppress from route steps
+ List<Object> allContextScoped = new ArrayList<>();
+ allContextScoped.addAll(contextScopedOnExceptions);
+ allContextScoped.addAll(contextScopedIntercepts);
+ allContextScoped.addAll(contextScopedInterceptFroms);
+ allContextScoped.addAll(contextScopedInterceptSendTos);
+ allContextScoped.addAll(contextScopedOnCompletions);
+
+ // a global (context-level) errorHandler is set on the CamelContext,
not on individual routes; it must be
+ // emitted as a top-level entry and not duplicated inside the routes
(route.getErrorHandler() is null for it);
+ // only emit it when dumping routes — rests, templates and route
configurations do not carry a context errorHandler
+ ErrorHandlerDefinition contextErrorHandler
+ = (definition instanceof RoutesDefinition || definition
instanceof RouteDefinition)
+ ? collectContextErrorHandler(context) : null;
YamlModelWriter writer = new YamlModelWriter() {
@Override
protected <T> void doWriteOutputs(JsonObject jo, List<T> list,
Function<T, JsonObject> writer) {
- if (list != null && !contextScoped.isEmpty()) {
- list = list.stream().filter(o ->
!containsInstance(contextScoped, o)).toList();
+ if (list != null && !allContextScoped.isEmpty()) {
+ list = list.stream().filter(o ->
!containsInstance(allContextScoped, o)).toList();
}
super.doWriteOutputs(jo, list, writer);
}
@@ -225,7 +273,23 @@ public class LwModelToYAMLDumper implements
ModelToYAMLDumper {
List<JsonObject> roots = new ArrayList<>();
try {
- for (OnExceptionDefinition oe : topLevel) {
+ // top-level errorHandler (global, context-level) before anything
else
+ if (contextErrorHandler != null) {
+
roots.add(writer.writeErrorHandlerDefinition(contextErrorHandler));
+ }
+ for (InterceptDefinition intercept : topLevelIntercepts) {
+ roots.add(writer.writeInterceptDefinition(intercept));
+ }
+ for (InterceptFromDefinition interceptFrom :
topLevelInterceptFroms) {
+ roots.add(writer.writeInterceptFromDefinition(interceptFrom));
+ }
+ for (InterceptSendToEndpointDefinition interceptSendTo :
topLevelInterceptSendTos) {
+
roots.add(writer.writeInterceptSendToEndpointDefinition(interceptSendTo));
+ }
+ for (OnCompletionDefinition onCompletion : topLevelOnCompletions) {
+ roots.add(writer.writeOnCompletionDefinition(onCompletion));
+ }
+ for (OnExceptionDefinition oe : topLevelOnExceptions) {
roots.add(writer.writeOnExceptionDefinition(oe));
}
if (definition instanceof RoutesDefinition rd) {
@@ -328,6 +392,94 @@ public class LwModelToYAMLDumper implements
ModelToYAMLDumper {
}
}
+ /**
+ * Collects the context scoped intercepts that were added to the route
when it was prepared. The persistent list on
+ * the route is used as the primary source because {@code
InterceptReifier} removes plain {@code intercept}
+ * definitions from route outputs during {@code context.start()}.
+ */
+ private static void collectContextScopedIntercepts(RouteDefinition route,
List<InterceptDefinition> answer) {
+ List<InterceptDefinition> persistent =
route.getContextScopedIntercepts();
+ if (persistent != null) {
+ for (InterceptDefinition intercept : persistent) {
+ if (!containsInstance(answer, intercept)) {
+ answer.add(intercept);
+ }
+ }
+ }
+ }
+
+ /**
+ * Collects the context scoped interceptFroms that were added to the
outputs of the route when it was prepared
+ */
+ private static void collectContextScopedInterceptFroms(RouteDefinition
route, List<InterceptFromDefinition> answer) {
+ for (var output : route.getOutputs()) {
+ if (output instanceof InterceptFromDefinition interceptFrom
+ && !interceptFrom.isRouteScoped()
+ && !containsInstance(answer, interceptFrom)) {
+ answer.add(interceptFrom);
+ }
+ }
+ }
+
+ /**
+ * Collects the context scoped interceptSendToEndpoints that were added to
the outputs of the route when it was
+ * prepared
+ */
+ private static void collectContextScopedInterceptSendTos(
+ RouteDefinition route, List<InterceptSendToEndpointDefinition>
answer) {
+ for (var output : route.getOutputs()) {
+ if (output instanceof InterceptSendToEndpointDefinition
interceptSendTo
+ && !interceptSendTo.isRouteScoped()
+ && !containsInstance(answer, interceptSendTo)) {
+ answer.add(interceptSendTo);
+ }
+ }
+ }
+
+ /**
+ * Collects the context scoped onCompletions that were recorded on the
route when it was prepared. Uses the
+ * persistent list rather than scanning outputs and checking {@code
!oc.isRouteScoped()}, because
+ * {@code routeScoped} already has runtime semantics in {@code
OnCompletionProcessor.shouldSkip()} and must not be
+ * altered.
+ */
+ private static void collectContextScopedOnCompletions(RouteDefinition
route, List<OnCompletionDefinition> answer) {
+ List<OnCompletionDefinition> persistent =
route.getContextScopedOnCompletions();
+ if (persistent != null) {
+ for (OnCompletionDefinition oc : persistent) {
+ if (!containsInstance(answer, oc)) {
+ answer.add(oc);
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns the context-level error handler as an {@link
ErrorHandlerDefinition} if one was explicitly set on the
+ * CamelContext using one of the built-in types, or {@code null}
otherwise. Custom {@code ErrorHandlerFactory}
+ * implementations cannot be serialized to YAML and are skipped.
+ */
+ private static ErrorHandlerDefinition
collectContextErrorHandler(CamelContext context) {
+ if (context == null) {
+ return null;
+ }
+ ErrorHandlerFactory factory =
context.getCamelContextExtension().getErrorHandlerFactory();
+ if (factory == null) {
+ // no explicit global error handler was configured; nothing to emit
+ return null;
+ }
+ // only the built-in types (DefaultErrorHandlerDefinition subclasses,
NoErrorHandlerDefinition,
+ // RefErrorHandlerDefinition) are known to the YAML writer; a custom
ErrorHandlerFactory cannot be
+ // serialized to YAML and would produce an empty errorHandler: {} —
skip it
+ if (!(factory instanceof DefaultErrorHandlerDefinition)
+ && !(factory instanceof NoErrorHandlerDefinition)
+ && !(factory instanceof RefErrorHandlerDefinition)) {
+ return null;
+ }
+ ErrorHandlerDefinition def = new ErrorHandlerDefinition();
+ def.setErrorHandlerType(factory);
+ return def;
+ }
+
private static boolean isInRouteConfiguration(CamelContext context,
OnExceptionDefinition oe) {
Model model = context != null ?
context.getCamelContextExtension().getContextPlugin(Model.class) : null;
if (model != null) {
@@ -340,6 +492,57 @@ public class LwModelToYAMLDumper implements
ModelToYAMLDumper {
return false;
}
+ private static boolean isInterceptInRouteConfiguration(CamelContext
context, InterceptDefinition intercept) {
+ Model model = context != null ?
context.getCamelContextExtension().getContextPlugin(Model.class) : null;
+ if (model != null) {
+ for (RouteConfigurationDefinition config :
model.getRouteConfigurationDefinitions()) {
+ if (containsInstance(config.getIntercepts(), intercept)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean isInterceptFromInRouteConfiguration(
+ CamelContext context, InterceptFromDefinition interceptFrom) {
+ Model model = context != null ?
context.getCamelContextExtension().getContextPlugin(Model.class) : null;
+ if (model != null) {
+ for (RouteConfigurationDefinition config :
model.getRouteConfigurationDefinitions()) {
+ if (containsInstance(config.getInterceptFroms(),
interceptFrom)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean isInterceptSendToInRouteConfiguration(
+ CamelContext context, InterceptSendToEndpointDefinition
interceptSendTo) {
+ Model model = context != null ?
context.getCamelContextExtension().getContextPlugin(Model.class) : null;
+ if (model != null) {
+ for (RouteConfigurationDefinition config :
model.getRouteConfigurationDefinitions()) {
+ if (containsInstance(config.getInterceptSendTos(),
interceptSendTo)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean isOnCompletionInRouteConfiguration(
+ CamelContext context, OnCompletionDefinition onCompletion) {
+ Model model = context != null ?
context.getCamelContextExtension().getContextPlugin(Model.class) : null;
+ if (model != null) {
+ for (RouteConfigurationDefinition config :
model.getRouteConfigurationDefinitions()) {
+ if (containsInstance(config.getOnCompletions(), onCompletion))
{
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
private static boolean containsInstance(List<?> list, Object instance) {
if (list == null) {
return false;
diff --git
a/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/ContextScopedTopLevelYamlDumpTest.java
b/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/ContextScopedTopLevelYamlDumpTest.java
new file mode 100644
index 000000000000..55d42e73c04a
--- /dev/null
+++
b/dsl/camel-yaml-dsl/camel-yaml-dsl/src/test/java/org/apache/camel/dsl/yaml/ContextScopedTopLevelYamlDumpTest.java
@@ -0,0 +1,387 @@
+/*
+ * 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.dsl.yaml;
+
+import java.util.List;
+
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.dsl.yaml.support.YamlTestSupport;
+import org.apache.camel.model.InterceptDefinition;
+import org.apache.camel.model.InterceptFromDefinition;
+import org.apache.camel.model.InterceptSendToEndpointDefinition;
+import org.apache.camel.model.OnCompletionDefinition;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.model.RoutesDefinition;
+import org.apache.camel.model.errorhandler.DeadLetterChannelDefinition;
+import org.apache.camel.yaml.LwModelToYAMLDumper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Tests that context-scoped EIPs (errorHandler, intercept, interceptFrom,
interceptSendToEndpoint, onCompletion) are
+ * written as top-level entries before the routes in the YAML dump, and not
duplicated in the steps of each route.
+ */
+class ContextScopedTopLevelYamlDumpTest extends YamlTestSupport {
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void topLevelInterceptIsDumpedAsTopLevel(boolean started) throws Exception
{
+ loadRoutes("""
+ - intercept:
+ steps:
+ - log:
+ message: "intercepted"
+ - route:
+ id: first
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ - route:
+ id: second
+ from:
+ uri: direct:second
+ steps:
+ - to: mock:second
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // written once as top-level, not in the steps of each route
+ assertThat(yaml).startsWith("- intercept:");
+ assertThat(yaml.split("intercept:", -1)).hasSize(2);
+ assertThat(yaml).contains("id: first").contains("id: second");
+
+ // the dump is valid for the YAML DSL schema and applies to all routes
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ loadRoutes(yaml);
+ assertThat(context.getRouteDefinitions()).hasSize(2);
+ for (String id : List.of("first", "second")) {
+ assertThat(context.getRouteDefinition(id).getOutputs().get(0))
+ .isInstanceOf(InterceptDefinition.class);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void topLevelInterceptFromIsDumpedAsTopLevel(boolean started) throws
Exception {
+ loadRoutes("""
+ - interceptFrom:
+ steps:
+ - log:
+ message: "intercepted from"
+ - route:
+ id: first
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ - route:
+ id: second
+ from:
+ uri: direct:second
+ steps:
+ - to: mock:second
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // written once as top-level, not in the steps of each route
+ assertThat(yaml).startsWith("- interceptFrom:");
+ assertThat(yaml.split("interceptFrom:", -1)).hasSize(2);
+ assertThat(yaml).contains("id: first").contains("id: second");
+
+ // the dump is valid for the YAML DSL schema and applies to all routes
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ loadRoutes(yaml);
+ assertThat(context.getRouteDefinitions()).hasSize(2);
+ for (String id : List.of("first", "second")) {
+ assertThat(context.getRouteDefinition(id).getOutputs().get(0))
+ .isInstanceOf(InterceptFromDefinition.class);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void topLevelInterceptSendToEndpointIsDumpedAsTopLevel(boolean started)
throws Exception {
+ loadRoutes("""
+ - interceptSendToEndpoint:
+ uri: mock:*
+ steps:
+ - log:
+ message: "intercepted send"
+ - route:
+ id: first
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ - route:
+ id: second
+ from:
+ uri: direct:second
+ steps:
+ - to: mock:second
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // written once as top-level, not in the steps of each route
+ assertThat(yaml).startsWith("- interceptSendToEndpoint:");
+ assertThat(yaml.split("interceptSendToEndpoint:", -1)).hasSize(2);
+ assertThat(yaml).contains("id: first").contains("id: second");
+
+ // the dump is valid for the YAML DSL schema and applies to all routes
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ loadRoutes(yaml);
+ assertThat(context.getRouteDefinitions()).hasSize(2);
+ for (String id : List.of("first", "second")) {
+ assertThat(context.getRouteDefinition(id).getOutputs().get(0))
+ .isInstanceOf(InterceptSendToEndpointDefinition.class);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void topLevelOnCompletionIsDumpedAsTopLevel(boolean started) throws
Exception {
+ loadRoutes("""
+ - onCompletion:
+ steps:
+ - log:
+ message: "completed"
+ - route:
+ id: first
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ - route:
+ id: second
+ from:
+ uri: direct:second
+ steps:
+ - to: mock:second
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // written once as top-level, not in the steps of each route
+ assertThat(yaml).startsWith("- onCompletion:");
+ assertThat(yaml.split("onCompletion:", -1)).hasSize(2);
+ assertThat(yaml).contains("id: first").contains("id: second");
+
+ // the dump is valid for the YAML DSL schema and applies to all routes
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ loadRoutes(yaml);
+ assertThat(context.getRouteDefinitions()).hasSize(2);
+ for (String id : List.of("first", "second")) {
+ assertThat(context.getRouteDefinition(id).getOutputs().get(0))
+ .isInstanceOf(OnCompletionDefinition.class);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void topLevelErrorHandlerIsDumpedAsTopLevel(boolean started) throws
Exception {
+ loadRoutes("""
+ - errorHandler:
+ deadLetterChannel:
+ deadLetterUri: log:dead
+ - route:
+ id: first
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ - route:
+ id: second
+ from:
+ uri: direct:second
+ steps:
+ - to: mock:second
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // written once as top-level, not inside any route
+ assertThat(yaml).startsWith("- errorHandler:");
+ assertThat(yaml.split("errorHandler:", -1)).hasSize(2);
+ assertThat(yaml).contains("deadLetterUri: log:dead");
+ assertThat(yaml).contains("id: first").contains("id: second");
+
+ // the dump is valid for the YAML DSL schema and the deadLetter
channel is active
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ loadRoutes(yaml);
+ assertThat(context.getRouteDefinitions()).hasSize(2);
+ assertThat(context.getCamelContextExtension().getErrorHandlerFactory())
+ .isInstanceOf(DeadLetterChannelDefinition.class);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void namedRouteConfigurationInterceptIsNotDumpedAsTopLevel(boolean
started) throws Exception {
+ // a named route configuration's intercept must NOT be emitted as a
top-level entry — it already
+ // appears inside the routeConfiguration block and must not be
duplicated as a top-level intercept
+ loadRoutes("""
+ - routeConfiguration:
+ id: myConfig
+ intercept:
+ - intercept:
+ steps:
+ - log:
+ message: "intercepted via config"
+ - route:
+ id: first
+ routeConfigurationId: myConfig
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // when dumping only routes, the route configuration's intercept must
NOT be hoisted to a top-level
+ // entry — it belongs to the named routeConfiguration, not to the
top-level route scope
+ assertThat(yaml).doesNotContain("- intercept:");
+ assertThat(yaml).contains("id: first");
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void namedRouteConfigurationOnCompletionIsNotDumpedAsTopLevel(boolean
started) throws Exception {
+ // a named route configuration's onCompletion must NOT be emitted as a
top-level entry — it already
+ // appears inside the routeConfiguration block and must not be
duplicated as a top-level onCompletion
+ loadRoutes("""
+ - routeConfiguration:
+ id: myConfig
+ onCompletion:
+ - onCompletion:
+ steps:
+ - log:
+ message: "completed via config"
+ - route:
+ id: first
+ routeConfigurationId: myConfig
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:first
+ """);
+ if (started) {
+ context.start();
+ }
+ String yaml = dumpRoutes();
+ if (started) {
+ context.stop();
+ }
+
+ // when dumping only routes, the route configuration's onCompletion
must NOT be hoisted to a top-level
+ // entry — it belongs to the named routeConfiguration, not to the
top-level route scope
+ assertThat(yaml).doesNotContain("- onCompletion:");
+ assertThat(yaml).contains("id: first");
+ }
+
+ @Test
+ void namedRouteConfigurationOnCompletionFiresAfterDumpReload() throws
Exception {
+ // a named route configuration's onCompletion must still fire at
runtime after a dump → reload cycle
+ // this verifies that the dump bookkeeping does not corrupt the
runtime routeScoped flag (CAMEL-25135);
+ // note: the route receives the exchange directly (direct:first is the
consumer route itself, not an
+ // indirect call through direct:); the full indirect-consumer case is
covered by RoutesConfigurationOnCompletionTest
+ loadRoutes("""
+ - routeConfiguration:
+ id: myConfig
+ onCompletion:
+ - onCompletion:
+ steps:
+ - to: mock:completion
+ - route:
+ id: first
+ routeConfigurationId: myConfig
+ from:
+ uri: direct:first
+ steps:
+ - to: mock:result
+ """);
+ context.start();
+
+ // first run: verify onCompletion fires
+ withMock("mock:completion", mock -> mock.expectedMessageCount(1));
+ withMock("mock:result", mock -> mock.expectedBodiesReceived("Hello
World"));
+ withTemplate(t -> t.to("direct:first").withBody("Hello World").send());
+ MockEndpoint.assertIsSatisfied(context);
+
+ // dump → reload cycle must preserve runtime behaviour
+ String dumped = dumpRoutes();
+
context.removeRouteDefinitions(List.copyOf(context.getRouteDefinitions()));
+ // reload the dumped routes — the named routeConfiguration was not
part of the dump
+ // (dumpRoutes only dumps routes, not routeConfigurations) so the
existing config remains
+ loadRoutes(dumped);
+
+ // second run: onCompletion must still fire after reload
+ context.getEndpoint("mock:completion", MockEndpoint.class).reset();
+ context.getEndpoint("mock:result", MockEndpoint.class).reset();
+ withMock("mock:completion", mock -> mock.expectedMessageCount(1));
+ withMock("mock:result", mock -> mock.expectedBodiesReceived("Bye
World"));
+ withTemplate(t -> t.to("direct:first").withBody("Bye World").send());
+ MockEndpoint.assertIsSatisfied(context);
+
+ context.stop();
+ }
+
+ private String dumpRoutes() throws Exception {
+ // as the routes are dumped by camel.main.dumpRoutes, which camel
validate normalize uses
+ RoutesDefinition routes = new RoutesDefinition();
+ for (RouteDefinition route : context.getRouteDefinitions()) {
+ routes.getRoutes().add(route);
+ }
+ return new LwModelToYAMLDumper().dumpModelAsYaml(context, routes,
false, true, false, false);
+ }
+}