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

davsclaus pushed a commit to branch CAMEL-28099-advicewith-merge-once
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 4b884e190edf33e01db711c1c5fd6b025319e927
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Dec 3 22:26:55 2026 +0100

    CAMEL-28099: camel-core - adviceWith merges the route configurations into 
the route once
    
    AdviceWith prepares the advised route again. The definitions that the first
    prepare merged in (from the route configurations) are in the route outputs,
    and the configurations were merged a second time: the onException,
    interceptFrom, interceptSendToEndpoint and intercept were in the route 
twice,
    and the intercept and interceptSendToEndpoint ran more than once.
    
    Preparing a route now keeps a context-scoped definition once when the route
    already has it (identity), so a second prepare is idempotent.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../apache/camel/model/RouteDefinitionHelper.java  |  33 ++-
 .../AdviceWithRouteConfigurationTest.java          | 233 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc    |   9 +
 3 files changed, 273 insertions(+), 2 deletions(-)

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..a8d4418889a1 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
@@ -569,7 +569,10 @@ public final class RouteDefinitionHelper {
             for (OnExceptionDefinition output : onExceptions) {
                 // these are context scoped on exceptions so set this flag
                 output.setRouteScoped(false);
-                abstracts.add(output);
+                // a route that is prepared again (adviceWith) has it already, 
as the first prepare merged it
+                if (!containsInstance(abstracts, output)) {
+                    abstracts.add(output);
+                }
             }
         }
 
@@ -620,6 +623,10 @@ public final class RouteDefinitionHelper {
         // 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 (contextScoped.contains(processor)) {
+                // a route that is prepared again (adviceWith) has it already, 
as the first prepare merged it
+                continue;
+            }
             if (processor instanceof InterceptSendToEndpointDefinition 
interceptSendToEndpointDefinition) {
                 if (interceptSendToEndpointDefinitions == null) {
                     interceptSendToEndpointDefinitions = new ArrayList<>();
@@ -761,16 +768,22 @@ public final class RouteDefinitionHelper {
             RouteDefinition route, List<ProcessorDefinition<?>> abstracts, 
List<ProcessorDefinition<?>> upper,
             List<OnCompletionDefinition> onCompletions) {
         List<OnCompletionDefinition> completions = new ArrayList<>();
+        boolean routeScoped = false;
 
         // find the route scoped onCompletions
         for (ProcessorDefinition out : abstracts) {
             if (out instanceof OnCompletionDefinition onCompletionDefinition) {
                 completions.add(onCompletionDefinition);
+                // a route that is prepared again (adviceWith) has the global 
onCompletions already, as the first
+                // prepare merged them, and they do not count as the route's 
own
+                if (onCompletions == null || !containsInstance(onCompletions, 
onCompletionDefinition)) {
+                    routeScoped = true;
+                }
             }
         }
 
         // only add global onCompletion if there are no route already
-        if (completions.isEmpty() && onCompletions != null) {
+        if (!routeScoped && onCompletions != null) {
             completions = onCompletions;
             // 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
@@ -781,6 +794,13 @@ public final class RouteDefinitionHelper {
                 route.addContextScopedOnCompletion(global);
                 initParent(global);
             }
+        } else if (onCompletions != null) {
+            // the global onCompletions that an earlier prepare merged are 
kept, and still context-scoped
+            for (OnCompletionDefinition completion : completions) {
+                if (containsInstance(onCompletions, completion)) {
+                    route.addContextScopedOnCompletion(completion);
+                }
+            }
         }
 
         // are there any completions to init at all?
@@ -791,6 +811,15 @@ public final class RouteDefinitionHelper {
         upper.addAll(completions);
     }
 
+    private static boolean containsInstance(List<?> list, Object element) {
+        for (Object o : list) {
+            if (o == element) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     private static void initSagaAndTransacted(
             List<ProcessorDefinition<?>> outputs, List<ProcessorDefinition<?>> 
abstracts,
             List<ProcessorDefinition<?>> lower) {
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithRouteConfigurationTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithRouteConfigurationTest.java
new file mode 100644
index 000000000000..9eacb5950fa4
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithRouteConfigurationTest.java
@@ -0,0 +1,233 @@
+/*
+ * 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.interceptor;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.NamedNode;
+import org.apache.camel.Processor;
+import org.apache.camel.Route;
+import org.apache.camel.builder.AdviceWith;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.builder.RouteConfigurationBuilder;
+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.OnExceptionDefinition;
+import org.apache.camel.model.ProcessorDefinition;
+import org.apache.camel.model.RouteConfigurationDefinition;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.model.TransactedDefinition;
+import org.apache.camel.spi.Policy;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * AdviceWith prepares the advised route again. The definitions that the first 
prepare merged into the route (from the
+ * route configurations and the RouteBuilder) must be in the route once, and 
run once.
+ */
+public class AdviceWithRouteConfigurationTest extends ContextTestSupport {
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    @Test
+    public void testRouteConfigurationStarted() throws Exception {
+        context.start();
+        context.addRoutesConfigurations(createRouteConfiguration());
+        context.addRoutes(createRoute());
+
+        RouteDefinition merged = advice();
+        assertMergedOnce(merged);
+        // the intercept is removed from the outputs when the route is created
+        assertThat(count(merged, InterceptDefinition.class)).isZero();
+        assertThat(merged.getContextScopedIntercepts()).hasSize(1);
+        assertThat(merged.getContextScopedOnCompletions()).hasSize(1);
+        
assertThat(merged.getAppliedRouteConfigurationIds()).containsExactly("myConfig");
+
+        assertRunsOnce();
+    }
+
+    @Test
+    public void testRouteConfigurationNotStarted() throws Exception {
+        context.addRoutesConfigurations(createRouteConfiguration());
+        context.addRoutes(createRoute());
+
+        RouteDefinition merged = advice();
+        assertMergedOnce(merged);
+        assertThat(count(merged, InterceptDefinition.class)).isOne();
+        assertThat(merged.getContextScopedIntercepts()).hasSize(1);
+        assertThat(merged.getContextScopedOnCompletions()).hasSize(1);
+        
assertThat(merged.getAppliedRouteConfigurationIds()).containsExactly("myConfig");
+
+        context.start();
+        assertRunsOnce();
+    }
+
+    @Test
+    public void testRouteBuilderStarted() throws Exception {
+        context.start();
+        context.addRoutes(createRouteWithBuilderLevelDefinitions());
+
+        RouteDefinition merged = advice();
+        assertMergedOnce(merged);
+
+        assertRunsOnceWithoutIntercept();
+    }
+
+    @Test
+    public void testRouteBuilderNotStarted() throws Exception {
+        context.addRoutes(createRouteWithBuilderLevelDefinitions());
+
+        RouteDefinition merged = advice();
+        assertMergedOnce(merged);
+
+        context.start();
+        assertRunsOnceWithoutIntercept();
+    }
+
+    @Test
+    public void testTransactedRouteConfiguration() throws Exception {
+        context.getRegistry().bind("myPolicy", new MyDummyPolicy());
+        context.start();
+        context.addRoutesConfigurations(new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                
routeConfiguration("myConfig").onException(IllegalArgumentException.class).handled(true).to("mock:error");
+            }
+        });
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("direct:start").routeId("foo").routeConfigurationId("myConfig")
+                        .setBody(simple("${body}-a"))
+                        .transacted("myPolicy")
+                        .setBody(simple("${body}-b"))
+                        .to("mock:result");
+            }
+        });
+
+        RouteDefinition merged = advice();
+        assertThat(count(merged, OnExceptionDefinition.class)).isOne();
+        assertThat(merged.getOutputs()).hasSize(2);
+        TransactedDefinition transacted = (TransactedDefinition) 
merged.getOutputs().get(1);
+        // the advice, the two setBody and the to
+        assertThat(transacted.getOutputs()).hasSize(4);
+
+        getMockEndpoint("mock:advice").expectedMessageCount(1);
+        getMockEndpoint("mock:result").expectedBodiesReceived("x-a-b");
+        getMockEndpoint("mock:error").expectedMessageCount(0);
+        template.sendBody("direct:start", "x");
+        assertMockEndpointsSatisfied();
+    }
+
+    private RouteDefinition advice() throws Exception {
+        return AdviceWith.adviceWith(context, "foo", a -> 
a.weaveAddFirst().to("mock:advice"));
+    }
+
+    private static void assertMergedOnce(RouteDefinition merged) {
+        assertThat(count(merged, OnExceptionDefinition.class)).isOne();
+        assertThat(count(merged, OnCompletionDefinition.class)).isOne();
+        assertThat(count(merged, InterceptFromDefinition.class)).isOne();
+        assertThat(count(merged, 
InterceptSendToEndpointDefinition.class)).isOne();
+    }
+
+    private static long count(RouteDefinition route, Class<? extends 
ProcessorDefinition<?>> type) {
+        // exact type, as InterceptFromDefinition extends InterceptDefinition
+        return route.getOutputs().stream().filter(o -> o.getClass() == 
type).count();
+    }
+
+    private void assertRunsOnce() throws Exception {
+        // the same count as the route written with the mock:advice step, 
without adviceWith (the intercept runs before
+        // each step, also the steps of the interceptFrom, 
interceptSendToEndpoint and onCompletion)
+        getMockEndpoint("mock:intercept").expectedMessageCount(11);
+        assertRunsOnceWithoutIntercept();
+    }
+
+    private void assertRunsOnceWithoutIntercept() throws Exception {
+        getMockEndpoint("mock:advice").expectedMessageCount(2);
+        getMockEndpoint("mock:result").expectedMessageCount(2);
+        getMockEndpoint("mock:interceptFrom").expectedMessageCount(2);
+        getMockEndpoint("mock:interceptSendTo").expectedMessageCount(2);
+        getMockEndpoint("mock:error").expectedBodiesReceived("Kaboom");
+        getMockEndpoint("mock:done").expectedMessageCount(2);
+
+        template.sendBody("direct:start", "Hello World");
+        template.sendBody("direct:start", "Kaboom");
+
+        assertMockEndpointsSatisfied();
+    }
+
+    private static RouteConfigurationBuilder createRouteConfiguration() {
+        return new RouteConfigurationBuilder() {
+            @Override
+            public void configuration() {
+                RouteConfigurationDefinition cfg = 
routeConfiguration("myConfig");
+                
cfg.onException(IllegalArgumentException.class).handled(true).to("mock:error");
+                cfg.onCompletion().to("mock:done");
+                cfg.interceptFrom("direct:start").to("mock:interceptFrom");
+                
cfg.interceptSendToEndpoint("mock:result").to("mock:interceptSendTo");
+                cfg.intercept().to("mock:intercept");
+            }
+        };
+    }
+
+    private static RouteBuilder createRoute() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("direct:start").routeId("foo").routeConfigurationId("myConfig")
+                        .to("mock:result")
+                        .filter(body().isEqualTo("Kaboom"))
+                        .throwException(new 
IllegalArgumentException("Forced"));
+            }
+        };
+    }
+
+    private static RouteBuilder createRouteWithBuilderLevelDefinitions() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
onException(IllegalArgumentException.class).handled(true).to("mock:error");
+                onCompletion().to("mock:done");
+                interceptFrom("direct:start").to("mock:interceptFrom");
+                
interceptSendToEndpoint("mock:result").to("mock:interceptSendTo");
+
+                from("direct:start").routeId("foo")
+                        .to("mock:result")
+                        .filter(body().isEqualTo("Kaboom"))
+                        .throwException(new 
IllegalArgumentException("Forced"));
+            }
+        };
+    }
+
+    private static final class MyDummyPolicy implements Policy {
+
+        @Override
+        public void beforeWrap(Route route, NamedNode definition) {
+            // noop
+        }
+
+        @Override
+        public Processor wrap(Route route, Processor processor) {
+            return processor;
+        }
+    }
+}
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..dd295c5eac9b 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
@@ -652,3 +652,12 @@ The polling consumer (`pollEnrich`, or `receive` of a 
`ConsumerTemplate`) now cl
 the polled exchange is done, instead of leaving it open. With `pollEnrich` 
this happens when the enriched exchange
 completes. With a `ConsumerTemplate`, call `doneUoW(exchange)` when you are 
done with the received exchange, as for any
 other polled endpoint.
+
+=== camel-core - adviceWith no longer merges the route configurations into the 
route a second time
+
+`AdviceWith` prepares the advised route again, and this merged the definitions 
of the route configurations into the
+route a second time. The advised route had each `onException`, `intercept`, 
`interceptFrom` and
+`interceptSendToEndpoint` of a route configuration twice, and an `intercept` 
or `interceptSendToEndpoint` of a route
+configuration ran more than once per step or call. They are now in the advised 
route once, and run once, as in the
+route without `adviceWith`. A test that expects the higher counts on the mock 
endpoints of such an intercept must be
+updated.

Reply via email to