This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch CAMEL-28100-intercept-recreate-main-path
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 0d68217ee62a468fae58239042b662c4c2edd99c
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Dec 3 22:27:16 2026 +0100

    CAMEL-28100: camel-core - intercept is kept when a route is created again, 
and is for the main route path
    
    InterceptReifier no longer removes its definition from the route outputs, 
so the intercept is created again when
    the route is created again (CamelContext restart, remove and add the same 
route definition, adviceWith).
    The first step of a route skips the onException, onCompletion, intercept, 
interceptFrom and interceptSendToEndpoint
    added to its outputs (backlog debugger _all_routes_ breakpoint).
    An intercept no longer intercepts the onCompletion step and its steps, like 
it does not intercept the steps of
    onException, interceptFrom and interceptSendToEndpoint, independent of the 
build order.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../main/docs/modules/eips/pages/intercept.adoc    |  18 +-
 .../apache/camel/model/RouteDefinitionHelper.java  |   9 +-
 .../org/apache/camel/reifier/InterceptReifier.java |  76 +++---
 .../org/apache/camel/reifier/ProcessorReifier.java |  51 ++++-
 ...letionAndInterceptAndOnExceptionGlobalTest.java |   6 +-
 .../OnCompletionAndInterceptGlobalTest.java        |   6 +-
 .../processor/OnCompletionAndInterceptTest.java    |   6 +-
 .../processor/intercept/InterceptMainPathTest.java | 255 +++++++++++++++++++++
 .../intercept/InterceptRouteLifecycleTest.java     | 158 +++++++++++++
 .../reifier/ProcessorReifierFirstStepTest.java     | 139 +++++++++++
 .../org/apache/camel/yaml/LwModelToYAMLDumper.java |  13 +-
 .../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc    |  10 +
 12 files changed, 698 insertions(+), 49 deletions(-)

diff --git 
a/core/camel-core-engine/src/main/docs/modules/eips/pages/intercept.adoc 
b/core/camel-core-engine/src/main/docs/modules/eips/pages/intercept.adoc
index e023a41d1ad3..831f46772ff7 100644
--- a/core/camel-core-engine/src/main/docs/modules/eips/pages/intercept.adoc
+++ b/core/camel-core-engine/src/main/docs/modules/eips/pages/intercept.adoc
@@ -7,7 +7,7 @@ xref:manual::exchange.adoc[Exchange]'s' while they are being 
routed.
 
 Camel supports three kinds of interceptors:
 
-* <<Intercept-Intercept, `intercept`>> that intercepts every processing step 
as they happen during routing
+* <<Intercept-Intercept, `intercept`>> that intercepts each processing step of 
the main route path as they happen during routing
 * <<Intercept-InterceptFrom, `interceptFrom`>> that intercepts only the 
incoming step (i.e., xref:from-eip.adoc[from])
 * <<Intercept-InterceptSendToEndpoint, `interceptSendToEndpoint`>> that 
intercepts only when an
 xref:manual::exchange.adoc[Exchange] is about to be sent to the given 
xref:message-endpoint.adoc[endpoint].
@@ -52,7 +52,7 @@ When using Apache Camel interceptors, the framework 
automatically populates exch
 == Using `intercept`
 
 The `Intercept` is intercepting the xref:manual::exchange.adoc[Exchange]
-on every processing step during routing.
+on each processing step of the main route path during routing.
 
 Given the following example:
 
@@ -115,6 +115,20 @@ before
 
 So in this example we intercept the `Exchange` twice.
 
+=== Which steps are intercepted
+
+The `intercept` is for the main route path: the steps of the routes, including 
the steps nested inside other EIPs
+such as xref:choice-eip.adoc[Content-Based Router] or 
xref:split-eip.adoc[Split].
+
+These steps are not intercepted:
+
+* the steps of xref:manual::exception-clause.adoc[onException]
+* the steps of xref:manual::oncompletion.adoc[onCompletion], and the 
`onCompletion` itself
+* the steps of `interceptFrom` and `interceptSendToEndpoint`
+* the `doTry`, `doCatch` and `doFinally` themselves (the steps inside them are 
intercepted)
+
+When there are several `intercept`, they run in the order they are declared in 
a `RouteBuilder`.
+
 === Controlling when to intercept using a predicate
 
 If you only want to intercept "sometimes", then you can use a 
xref:manual::predicate.adoc[predicate].
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 c8e293f77e35..6beffc4f3a5b 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
@@ -651,12 +651,17 @@ public final class RouteDefinitionHelper {
 
         // configure intercept
         if (intercepts != null && !intercepts.isEmpty()) {
+            Set<InterceptDefinition> added = Collections.newSetFromMap(new 
IdentityHashMap<>());
             for (InterceptDefinition intercept : intercepts) {
+                if (!added.add(intercept)) {
+                    // the same intercept once, such as when a route is 
prepared again (adviceWith), and the intercept of
+                    // a route configuration is both in the outputs of the 
route and merged again from the configuration
+                    continue;
+                }
                 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
+                    // keep a reference on the route definition, so the YAML 
dumper can find the context-scoped intercepts
                     route.addContextScopedIntercept(intercept);
                 }
                 // init the parent
diff --git 
a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptReifier.java
 
b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptReifier.java
index 101f5e7c7cf0..b98e20fcb272 100644
--- 
a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptReifier.java
+++ 
b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/InterceptReifier.java
@@ -25,7 +25,6 @@ import org.apache.camel.Route;
 import org.apache.camel.model.InterceptDefinition;
 import org.apache.camel.model.ProcessorDefinition;
 import org.apache.camel.model.ProcessorDefinitionHelper;
-import org.apache.camel.model.RouteDefinition;
 import org.apache.camel.processor.FilterProcessor;
 import org.apache.camel.processor.Pipeline;
 import org.apache.camel.spi.InterceptStrategy;
@@ -51,44 +50,55 @@ public class InterceptReifier extends 
ProcessorReifier<InterceptDefinition> {
         }
         final Processor output = child;
 
-        // add the output as an intercept strategy to the route context so its
-        // invoked on each processing step
-        route.getInterceptStrategies().add(new InterceptStrategy() {
-            private Processor interceptedTarget;
+        // add the output as an intercept strategy to the route, so it is 
invoked on each processing step of the main
+        // route path (the steps of onException, onCompletion, interceptFrom 
and interceptSendToEndpoint are not
+        // intercepted, see ProcessorReifier)
+        route.getInterceptStrategies().add(new 
InterceptDefinitionStrategy(route, output));
 
-            public Processor wrapProcessorInInterceptors(
-                    CamelContext context, NamedNode definition, Processor 
target, Processor nextTarget)
-                    throws Exception {
+        // the intercept is not a processor in the route (the definition is 
abstract, and is kept in the route, so the
+        // intercept is created again when the route is created again, such as 
when CamelContext is restarted)
+        // and return no processor to invoke next from me
+        return null;
+    }
 
-                // store the target we are intercepting
-                this.interceptedTarget = target;
+    /**
+     * The intercept strategy of an intercept definition, which runs the 
output of the intercept before each processing
+     * step of the main route path.
+     */
+    static final class InterceptDefinitionStrategy implements 
InterceptStrategy {
 
-                Processor p = exchange -> {
-                    
exchange.setProperty(ExchangePropertyKey.INTERCEPTED_ROUTE_ID,
-                            
ProcessorDefinitionHelper.getRouteId(definition.getParent()));
-                    
exchange.setProperty(ExchangePropertyKey.INTERCEPTED_NODE_ID, 
definition.getId());
-                    
exchange.setProperty(ExchangePropertyKey.INTERCEPTED_ROUTE_ENDPOINT_URI,
-                            route.getEndpoint().getEndpointUri());
-                };
+        private final Route route;
+        private final Processor output;
 
-                // wrap in a pipeline so we continue routing to the next
-                if (interceptedTarget != null) {
-                    return Pipeline.newInstance(context, p, output, 
interceptedTarget);
-                } else {
-                    return Pipeline.newInstance(context, p, output);
-                }
-            }
+        InterceptDefinitionStrategy(Route route, Processor output) {
+            this.route = route;
+            this.output = output;
+        }
+
+        @Override
+        public Processor wrapProcessorInInterceptors(
+                CamelContext context, NamedNode definition, Processor target, 
Processor nextTarget)
+                throws Exception {
 
-            @Override
-            public String toString() {
-                return "intercept[" + (interceptedTarget != null ? 
interceptedTarget : output) + "]";
+            Processor p = exchange -> {
+                exchange.setProperty(ExchangePropertyKey.INTERCEPTED_ROUTE_ID,
+                        
ProcessorDefinitionHelper.getRouteId(definition.getParent()));
+                exchange.setProperty(ExchangePropertyKey.INTERCEPTED_NODE_ID, 
definition.getId());
+                
exchange.setProperty(ExchangePropertyKey.INTERCEPTED_ROUTE_ENDPOINT_URI,
+                        route.getEndpoint().getEndpointUri());
+            };
+
+            // wrap in a pipeline so we continue routing to the next
+            if (target != null) {
+                return Pipeline.newInstance(context, p, output, target);
+            } else {
+                return Pipeline.newInstance(context, p, output);
             }
-        });
+        }
 
-        // remove me from the route, so I am not invoked in a regular route 
path
-        ((RouteDefinition) route.getRoute()).getOutputs().remove(definition);
-        // and return no processor to invoke next from me
-        return null;
+        @Override
+        public String toString() {
+            return "intercept[" + output + "]";
+        }
     }
-
 }
diff --git 
a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/ProcessorReifier.java
 
b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/ProcessorReifier.java
index e3ec310310d5..b1f9e3d5a746 100644
--- 
a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/ProcessorReifier.java
+++ 
b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/ProcessorReifier.java
@@ -674,7 +674,16 @@ public abstract class ProcessorReifier<T extends 
ProcessorDefinition<?>> extends
         // camel context, route context, local
         List<InterceptStrategy> interceptors = new ArrayList<>();
         
interceptors.addAll(camelContext.getCamelContextExtension().getInterceptStrategies());
-        interceptors.addAll(route.getInterceptStrategies());
+        if (isMainRoutePath(definition) && (child == null || 
isMainRoutePath(child))) {
+            interceptors.addAll(route.getInterceptStrategies());
+        } else {
+            // an intercept is for the steps of the main route path only
+            for (InterceptStrategy strategy : route.getInterceptStrategies()) {
+                if (!(strategy instanceof 
InterceptReifier.InterceptDefinitionStrategy)) {
+                    interceptors.add(strategy);
+                }
+            }
+        }
         interceptors.addAll(definition.getInterceptStrategies());
 
         // force the creation of an id
@@ -699,8 +708,8 @@ public abstract class ProcessorReifier<T extends 
ProcessorDefinition<?>> extends
         // set the child before init the channel
         RouteDefinition route = ProcessorDefinitionHelper.getRoute(definition);
         boolean first = false;
-        if (route != null && !route.getOutputs().isEmpty()) {
-            first = route.getOutputs().get(0) == definition;
+        if (route != null) {
+            first = firstRouteStep(route) == definition;
         }
         // special for aggregate which output are regarded as a new first
         NamedNode targetOutputDef = child != null ? child : definition;
@@ -725,6 +734,42 @@ public abstract class ProcessorReifier<T extends 
ProcessorDefinition<?>> extends
         return channel;
     }
 
+    /**
+     * Whether the node is on the main route path, which is not the case for 
the steps of onException, onCompletion,
+     * interceptFrom and interceptSendToEndpoint (and these nodes themselves).
+     */
+    private static boolean isMainRoutePath(NamedNode node) {
+        while (node != null) {
+            if (isOffMainRoutePath(node)) {
+                return false;
+            }
+            node = node.getParent();
+        }
+        return true;
+    }
+
+    /**
+     * The first step of the route the route author wrote, which is not one of 
the onException, onCompletion, intercept,
+     * interceptFrom and interceptSendToEndpoint that are added to the outputs 
of the route when it is prepared.
+     */
+    private static ProcessorDefinition<?> firstRouteStep(RouteDefinition 
route) {
+        for (ProcessorDefinition<?> output : route.getOutputs()) {
+            if (!(isOffMainRoutePath(output) || output instanceof 
InterceptDefinition)) {
+                return output;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * The onException, onCompletion, interceptFrom and 
interceptSendToEndpoint are not on the main route path. (The
+     * outputs of an intercept are intercepted by the intercepts that are 
created before it.)
+     */
+    private static boolean isOffMainRoutePath(NamedNode node) {
+        return node instanceof OnExceptionDefinition || node instanceof 
OnCompletionDefinition
+                || node instanceof InterceptFromDefinition || node instanceof 
InterceptSendToEndpointDefinition;
+    }
+
     /**
      * Wraps the given channel in error handler (if error handler is inherited)
      *
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptAndOnExceptionGlobalTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptAndOnExceptionGlobalTest.java
index d16cc81d97a1..a106a1d1f869 100644
--- 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptAndOnExceptionGlobalTest.java
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptAndOnExceptionGlobalTest.java
@@ -32,7 +32,8 @@ public class OnCompletionAndInterceptAndOnExceptionGlobalTest 
extends ContextTes
     @Test
     public void testSynchronizeComplete() throws Exception {
         getMockEndpoint("mock:exception").expectedMessageCount(0);
-        getMockEndpoint("mock:intercept").expectedMessageCount(5);
+        // the steps of onCompletion and onException are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(2);
         getMockEndpoint("mock:sync").expectedBodiesReceived("Bye World");
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
@@ -47,7 +48,8 @@ public class OnCompletionAndInterceptAndOnExceptionGlobalTest 
extends ContextTes
     @Test
     public void testSynchronizeFailure() throws Exception {
         getMockEndpoint("mock:exception").expectedMessageCount(1);
-        getMockEndpoint("mock:intercept").expectedMessageCount(4);
+        // the steps of onCompletion and onException are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(1);
         getMockEndpoint("mock:sync").expectedMessageCount(1);
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptGlobalTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptGlobalTest.java
index df42631b7b88..de5be45e6cdf 100644
--- 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptGlobalTest.java
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptGlobalTest.java
@@ -31,7 +31,8 @@ public class OnCompletionAndInterceptGlobalTest extends 
ContextTestSupport {
 
     @Test
     public void testSynchronizeComplete() throws Exception {
-        getMockEndpoint("mock:intercept").expectedMinimumMessageCount(4);
+        // the steps of onCompletion are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(2);
         getMockEndpoint("mock:sync").expectedBodiesReceived("Bye World");
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
@@ -45,7 +46,8 @@ public class OnCompletionAndInterceptGlobalTest extends 
ContextTestSupport {
 
     @Test
     public void testSynchronizeFailure() throws Exception {
-        getMockEndpoint("mock:intercept").expectedMinimumMessageCount(4);
+        // the steps of onCompletion are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(1);
         getMockEndpoint("mock:sync").expectedMessageCount(1);
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptTest.java
index 5764a33ca42b..d76fc7532fe9 100644
--- 
a/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptTest.java
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionAndInterceptTest.java
@@ -31,7 +31,8 @@ public class OnCompletionAndInterceptTest extends 
ContextTestSupport {
 
     @Test
     public void testSynchronizeComplete() throws Exception {
-        getMockEndpoint("mock:intercept").expectedMessageCount(5);
+        // the steps of onCompletion are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(2);
         getMockEndpoint("mock:sync").expectedBodiesReceived("Bye World");
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
@@ -45,7 +46,8 @@ public class OnCompletionAndInterceptTest extends 
ContextTestSupport {
 
     @Test
     public void testSynchronizeFailure() throws Exception {
-        getMockEndpoint("mock:intercept").expectedMessageCount(4);
+        // the steps of onCompletion are not intercepted
+        getMockEndpoint("mock:intercept").expectedMessageCount(1);
         getMockEndpoint("mock:sync").expectedMessageCount(1);
         
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, 
true);
 
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptMainPathTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptMainPathTest.java
new file mode 100644
index 000000000000..e7ebdd240968
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptMainPathTest.java
@@ -0,0 +1,255 @@
+/*
+ * 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.processor.intercept;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePropertyKey;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.builder.RouteConfigurationBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Which steps an intercept intercepts: the steps of the main route path, and 
not the steps of onException,
+ * onCompletion, interceptFrom and interceptSendToEndpoint. Also the order in 
which several intercepts run.
+ */
+public class InterceptMainPathTest extends ContextTestSupport {
+
+    private final List<String> events = new CopyOnWriteArrayList<>();
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    private void intercepted(Exchange exchange) {
+        events.add("intercept:" + 
exchange.getProperty(ExchangePropertyKey.INTERCEPTED_NODE_ID, String.class));
+    }
+
+    private List<String> send(String uri) {
+        events.clear();
+        template.send(uri, e -> e.getMessage().setBody("Hello"));
+        return List.copyOf(events);
+    }
+
+    @Test
+    public void testRouteSteps() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+
+                from("direct:a").routeId("a")
+                        .process(e -> events.add("a1")).id("a1")
+                        .filter(constant(true)).id("filter")
+                        .process(e -> events.add("a2")).id("a2")
+                        .end()
+                        .process(e -> events.add("a3")).id("a3");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "a1", "intercept:filter", 
"intercept:a2", "a2", "intercept:a3", "a3"),
+                send("direct:a"));
+    }
+
+    @Test
+    public void testOnExceptionStepsAreNotIntercepted() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+                onException(IllegalArgumentException.class).handled(true)
+                        .process(e -> events.add("oe1")).id("oe1")
+                        .process(e -> events.add("oe2")).id("oe2");
+
+                from("direct:a").routeId("a")
+                        .process(e -> events.add("a1")).id("a1")
+                        .throwException(new 
IllegalArgumentException("Forced")).id("boom");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "a1", "intercept:boom", "oe1", 
"oe2"), send("direct:a"));
+    }
+
+    @Test
+    public void testInterceptFromStepsAreNotIntercepted() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+                interceptFrom().process(e -> events.add("if1")).id("if1");
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("if1", "intercept:a1", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testInterceptSendToEndpointStepsAreNotIntercepted() throws 
Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+                interceptSendToEndpoint("mock:target").process(e -> 
events.add("ise1")).id("ise1");
+
+                from("direct:a").routeId("a").to("mock:target").id("a1");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "ise1"), send("direct:a"));
+    }
+
+    @Test
+    public void testOnCompletionStepsAreNotIntercepted() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+                onCompletion().id("oc")
+                        .process(e -> events.add("oc1")).id("oc1")
+                        .process(e -> events.add("oc2")).id("oc2");
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "a1", "oc1", "oc2"), 
send("direct:a"));
+    }
+
+    @Test
+    public void testRouteScopedOnCompletionStepsAreNotIntercepted() throws 
Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> intercepted(e));
+
+                from("direct:a").routeId("a")
+                        .onCompletion().id("oc")
+                        .choice().when(constant(true))
+                        .process(e -> events.add("oc1")).id("oc1")
+                        .end()
+                        .end()
+                        .process(e -> events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "a1", "oc1"), send("direct:a"));
+    }
+
+    @Test
+    public void testRouteConfiguration() throws Exception {
+        context.addRoutes(new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                routeConfiguration().intercept().process(e -> intercepted(e));
+                routeConfiguration().onCompletion().process(e -> 
events.add("oc1")).id("oc1");
+                
routeConfiguration().onException(IllegalArgumentException.class).handled(true)
+                        .process(e -> events.add("oe1")).id("oe1");
+            }
+        });
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:a").routeId("a")
+                        .process(e -> events.add("a1")).id("a1")
+                        .throwException(new 
IllegalArgumentException("Forced")).id("boom");
+            }
+        });
+        context.start();
+
+        assertEquals(List.of("intercept:a1", "a1", "intercept:boom", "oe1", 
"oc1"), send("direct:a"));
+    }
+
+    @Test
+    public void testOrderOfSeveralIntercepts() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().onWhen(e -> record("first")).to("mock:never");
+                intercept().onWhen(e -> record("second")).to("mock:never");
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        // the intercepts of a RouteBuilder run in the order they are declared
+        assertEquals(List.of("first", "second", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testOrderOfSeveralInterceptsInRouteConfiguration() throws 
Exception {
+        context.addRoutes(new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                routeConfiguration().intercept().onWhen(e -> 
record("config1")).to("mock:never");
+                routeConfiguration().intercept().onWhen(e -> 
record("config2")).to("mock:never");
+            }
+        });
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().onWhen(e -> record("builder")).to("mock:never");
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        // the intercepts of a route configuration run in reverse declaration 
order, before those of the RouteBuilder
+        assertEquals(List.of("config2", "config1", "builder", "a1"), 
send("direct:a"));
+    }
+
+    @Test
+    public void testInterceptInterceptsTheOutputOfTheInterceptsAfterIt() 
throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> events.add("first")).id("first");
+                intercept().process(e -> events.add("second")).id("second");
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+
+        // the first intercept also intercepts the output of the second 
intercept, but not the other way around
+        assertEquals(List.of("first", "first", "second", "a1"), 
send("direct:a"));
+    }
+
+    /**
+     * Records the intercept in its onWhen predicate, which returns false, so 
the intercepts are recorded without
+     * running their outputs (which other intercepts would intercept)
+     */
+    private boolean record(String name) {
+        events.add(name);
+        return false;
+    }
+}
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptRouteLifecycleTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptRouteLifecycleTest.java
new file mode 100644
index 000000000000..3d8163d85a6c
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptRouteLifecycleTest.java
@@ -0,0 +1,158 @@
+/*
+ * 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.processor.intercept;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.AdviceWith;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.builder.RouteConfigurationBuilder;
+import org.apache.camel.model.ModelCamelContext;
+import org.apache.camel.model.RouteDefinition;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * The intercept of a route when the route is stopped and started, when it is 
created again from the same definition,
+ * and when CamelContext is restarted.
+ */
+public class InterceptRouteLifecycleTest extends ContextTestSupport {
+
+    private final List<String> events = new CopyOnWriteArrayList<>();
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    private List<String> send(String uri) {
+        events.clear();
+        template.send(uri, e -> e.getMessage().setBody("Hello"));
+        return List.copyOf(events);
+    }
+
+    private void restartContext() {
+        context.stop();
+        context.start();
+        // the producer template caches the producers of the endpoints from 
before the restart
+        template.stop();
+        template = context.createProducerTemplate();
+    }
+
+    private void addRoute() throws Exception {
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().process(e -> events.add("intercept"));
+
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+    }
+
+    @Test
+    public void testStopStartRoute() throws Exception {
+        addRoute();
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        context.getRouteController().stopRoute("a");
+        context.getRouteController().startRoute("a");
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testCamelContextRestart() throws Exception {
+        addRoute();
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        restartContext();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        restartContext();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testCamelContextRestartRouteConfiguration() throws Exception {
+        context.addRoutes(new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                routeConfiguration().intercept().process(e -> 
events.add("intercept"));
+            }
+        });
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        restartContext();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testRemoveAndAddSameRouteDefinition() throws Exception {
+        addRoute();
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        ModelCamelContext mcc = (ModelCamelContext) context;
+        RouteDefinition definition = mcc.getRouteDefinition("a");
+        mcc.removeRouteDefinition(definition);
+        mcc.addRouteDefinition(definition);
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+    }
+
+    @Test
+    public void testAdviceWithAfterStart() throws Exception {
+        addRoute();
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        AdviceWith.adviceWith(context, "a", a -> a.weaveAddLast().process(e -> 
events.add("a2")).id("a2"));
+        assertEquals(List.of("intercept", "a1", "intercept", "a2"), 
send("direct:a"));
+    }
+
+    @Test
+    public void testAdviceWithAfterStartRouteConfiguration() throws Exception {
+        context.addRoutes(new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                routeConfiguration().intercept().process(e -> 
events.add("intercept"));
+            }
+        });
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:a").routeId("a").process(e -> 
events.add("a1")).id("a1");
+            }
+        });
+        context.start();
+        assertEquals(List.of("intercept", "a1"), send("direct:a"));
+
+        AdviceWith.adviceWith(context, "a", a -> a.weaveAddLast().process(e -> 
events.add("a2")).id("a2"));
+        assertEquals(List.of("intercept", "a1", "intercept", "a2"), 
send("direct:a"));
+    }
+}
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/reifier/ProcessorReifierFirstStepTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/reifier/ProcessorReifierFirstStepTest.java
new file mode 100644
index 000000000000..3bdbe3551393
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/reifier/ProcessorReifierFirstStepTest.java
@@ -0,0 +1,139 @@
+/*
+ * 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.reifier;
+
+import java.util.Set;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.debugger.DefaultBacklogDebugger;
+import org.apache.camel.spi.BacklogDebugger;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * The first step of a route is the first step the route author wrote, not an 
onException, onCompletion, intercept,
+ * interceptFrom or interceptSendToEndpoint that is added to the outputs of 
the route when it is prepared. The backlog
+ * debugger uses it for the initial breakpoint on all routes.
+ */
+public class ProcessorReifierFirstStepTest extends ContextTestSupport {
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    private void assertFirstStep(RouteBuilder builder) throws Exception {
+        // the debugger is in standby, so it does not suspend any message
+        BacklogDebugger debugger = 
DefaultBacklogDebugger.createDebugger(context);
+        debugger.setStandby(true);
+        debugger.setInitialBreakpoints(BacklogDebugger.BREAKPOINT_ALL_ROUTES);
+        context.addService(debugger);
+        context.setDebugging(true);
+
+        context.addRoutes(builder);
+        context.start();
+        assertEquals(Set.of("a1"), debugger.getBreakpoints());
+    }
+
+    @Test
+    public void testRoute() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testOnException() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                onException(Exception.class).to("mock:error").id("error");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testOnCompletion() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                onCompletion().id("oc").to("mock:done").id("done");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testIntercept() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                intercept().id("icp").to("mock:intercept").id("intercepted");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testInterceptFrom() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                interceptFrom().id("ifrom").to("mock:from").id("from");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testInterceptSendToEndpoint() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
interceptSendToEndpoint("mock:a2").id("ise").to("mock:sent").id("sent");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+
+    @Test
+    public void testAll() throws Exception {
+        assertFirstStep(new RouteBuilder() {
+            @Override
+            public void configure() {
+                onException(Exception.class).to("mock:error").id("error");
+                onCompletion().id("oc").to("mock:done").id("done");
+                intercept().id("icp").to("mock:intercept").id("intercepted");
+                interceptFrom().id("ifrom").to("mock:from").id("from");
+                
interceptSendToEndpoint("mock:a2").id("ise").to("mock:sent").id("sent");
+
+                
from("direct:a").routeId("a").to("mock:a1").id("a1").to("mock:a2").id("a2");
+            }
+        });
+    }
+}
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 0d6158b81cf5..4159c57be3f6 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
@@ -393,9 +393,9 @@ 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()}.
+     * Collects the context scoped intercepts that were added to the outputs 
of the route when it was prepared: those on
+     * the list the route keeps when it is prepared, and those in the outputs 
that are not route scoped (such as when
+     * the route was prepared again by adviceWith, which resets that list).
      */
     private static void collectContextScopedIntercepts(RouteDefinition route, 
List<InterceptDefinition> answer) {
         List<InterceptDefinition> persistent = 
route.getContextScopedIntercepts();
@@ -406,6 +406,13 @@ public class LwModelToYAMLDumper implements 
ModelToYAMLDumper {
                 }
             }
         }
+        for (var output : route.getOutputs()) {
+            // an interceptFrom is an InterceptDefinition as well, and is 
collected on its own
+            if (output instanceof InterceptDefinition intercept && !(output 
instanceof InterceptFromDefinition)
+                    && !intercept.isRouteScoped() && !containsInstance(answer, 
intercept)) {
+                answer.add(intercept);
+            }
+        }
     }
 
     /**
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
index a3638dcc0c47..c8849475f3e2 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
@@ -13,6 +13,16 @@ See the xref:camel-upgrade-recipes-tool.adoc[documentation] 
page for details.
 
 == Upgrading Camel 4.24 to 4.25
 
+=== camel-core - intercept no longer intercepts the steps of onCompletion
+
+The xref:eips:intercept.adoc[intercept] is for the main route path. The 
`onCompletion` and the steps inside an
+`onCompletion` are no longer intercepted, as the steps of `onException`, 
`interceptFrom` and
+`interceptSendToEndpoint` already were not. For example, a route with two 
steps and an `onCompletion` with two steps
+was intercepted 5 times, and is now intercepted 2 times.
+
+The `intercept` is now also kept when a route is created again from its 
definition, such as when `CamelContext` is
+stopped and started again, or when a route definition is removed and added 
again. Before, the intercept was lost.
+
 === camel-opentelemetry2 - OTEL_BAGGAGE_ headers removed
 
 The deprecated `OTEL_BAGGAGE_<name>` message headers are no longer converted 
into OpenTelemetry baggage.

Reply via email to