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

davsclaus pushed a commit to branch CAMEL-27364-kamelet-deps-before-routes
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 3e1e0d722f49a5647dcade7423a5cbc52e4a5077
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 22 10:09:08 2026 +0100

    CAMEL-27364: camel-jbang - the dependencies of a Kamelet are downloaded 
when a route that uses it is added, so the route can use their classes
    
    The dependencies of a Kamelet were downloaded when its template was
    loaded, which is when the route of the Kamelet is created: after all the
    routes, when the CamelContext is initialized. A route with a doCatch on
    a class of such a dependency, such as org.apache.cxf.binding.soap.SoapFault
    after a Kamelet that declares camel:cxf-soap, then failed to be created
    with ClassNotFoundException, unless --dep=camel:cxf-soap was given.
    
    DependencyDownloaderKamelet is now also a ModelLifecycleStrategy: when a
    route definition is added, the Kamelets of its kamelet: endpoints are
    looked up in the Kamelet location, as the kamelet component does, and
    their dependencies are downloaded, before the route is created.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Claus Ibsen <[email protected]>
---
 .../main/download/DependencyDownloaderKamelet.java | 152 ++++++++++++++++++++-
 .../download/DependencyDownloaderKameletTest.java  | 143 +++++++++++++++++++
 2 files changed, 294 insertions(+), 1 deletion(-)

diff --git 
a/dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloaderKamelet.java
 
b/dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloaderKamelet.java
index cc16f250f10f..a64917a5cc47 100644
--- 
a/dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloaderKamelet.java
+++ 
b/dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/DependencyDownloaderKamelet.java
@@ -16,25 +16,39 @@
  */
 package org.apache.camel.main.download;
 
+import java.io.File;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelContextAware;
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.kamelet.Kamelet;
 import org.apache.camel.component.kamelet.KameletComponent;
 import org.apache.camel.dsl.yaml.YamlRoutesBuilderLoaderSupport;
 import org.apache.camel.dsl.yaml.common.YamlDeserializationContext;
 import org.apache.camel.dsl.yaml.common.YamlDeserializerSupport;
 import org.apache.camel.main.util.VersionHelper;
+import org.apache.camel.model.EndpointRequiredDefinition;
+import org.apache.camel.model.ModelCamelContext;
+import org.apache.camel.model.ModelLifecycleStrategy;
+import org.apache.camel.model.ProcessorDefinitionHelper;
+import org.apache.camel.model.RouteDefinition;
+import org.apache.camel.model.RouteTemplateDefinition;
 import org.apache.camel.spi.Resource;
+import org.apache.camel.spi.ResourceLoader;
 import org.apache.camel.spi.RouteTemplateLoaderListener;
+import org.apache.camel.support.PluginHelper;
 import org.apache.camel.support.service.ServiceHelper;
 import org.apache.camel.support.service.ServiceSupport;
 import org.apache.camel.tooling.maven.MavenGav;
+import org.apache.camel.util.FileUtil;
+import org.apache.camel.util.URISupport;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.snakeyaml.engine.v2.nodes.Node;
@@ -46,13 +60,21 @@ import static 
org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.nodeAt;
 
 /**
  * To automatic downloaded dependencies that Kamelets requires.
+ *
+ * The dependencies of a Kamelet are downloaded when a route that uses the 
Kamelet is added, before the route is
+ * created: the route can then use the classes of these dependencies, such as 
an exception class in a doCatch. The route
+ * of the Kamelet itself is created later, when the CamelContext is 
initialized.
  */
 public final class DependencyDownloaderKamelet extends ServiceSupport
-        implements CamelContextAware, RouteTemplateLoaderListener {
+        implements CamelContextAware, RouteTemplateLoaderListener, 
ModelLifecycleStrategy {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(DependencyDownloaderKamelet.class);
 
     private String kameletsVersion;
     private KameletDependencyDownloader downloader;
     private CamelContext camelContext;
+    // the Kamelets whose dependencies are downloaded already, when a route 
that uses them is added
+    private final Set<String> kamelets = ConcurrentHashMap.newKeySet();
 
     public DependencyDownloaderKamelet(CamelContext camelContext, String 
kameletsVersion) {
         this.camelContext = camelContext;
@@ -75,6 +97,9 @@ public final class DependencyDownloaderKamelet extends 
ServiceSupport
         if (comp instanceof KameletComponent kc) {
             kc.setRouteTemplateLoaderListener(this);
         }
+        if (camelContext instanceof ModelCamelContext mcc) {
+            mcc.addModelLifecycleStrategy(this);
+        }
     }
 
     @Override
@@ -109,6 +134,131 @@ public final class DependencyDownloaderKamelet extends 
ServiceSupport
         }
     }
 
+    @Override
+    public void onAddRouteDefinition(RouteDefinition routeDefinition) {
+        // the Kamelets of the route are created after all the routes, when 
the CamelContext is initialized: their
+        // dependencies are downloaded now, so the route can use their classes 
(CAMEL-27364)
+        if (downloader == null) {
+            return;
+        }
+        List<String> uris = new ArrayList<>();
+        if (routeDefinition.getInput() != null) {
+            uris.add(routeDefinition.getInput().getEndpointUri());
+        }
+        for (EndpointRequiredDefinition erd : 
ProcessorDefinitionHelper.filterTypeInOutputs(routeDefinition.getOutputs(),
+                EndpointRequiredDefinition.class)) {
+            uris.add(erd.getEndpointUri());
+        }
+        for (String uri : uris) {
+            String name = kameletName(uri);
+            if (name != null && kamelets.add(name)) {
+                try {
+                    Resource resource = resolveKamelet(name, 
kameletLocation(uri));
+                    if (resource != null) {
+                        LOG.debug("Downloading the dependencies of Kamelet: {} 
used by route: {}", name,
+                                routeDefinition.getRouteId());
+                        loadRouteTemplate(resource);
+                    }
+                } catch (Exception e) {
+                    // the dependencies are then downloaded when the Kamelet 
is loaded, which reports the error
+                    LOG.debug("Cannot download the dependencies of Kamelet: {} 
due to: {}", name, e.getMessage(), e);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void onRemoveRouteDefinition(RouteDefinition routeDefinition) {
+        // noop
+    }
+
+    @Override
+    public void onAddRouteTemplateDefinition(RouteTemplateDefinition 
routeTemplateDefinition) {
+        // noop
+    }
+
+    @Override
+    public void onRemoveRouteTemplateDefinition(RouteTemplateDefinition 
routeTemplateDefinition) {
+        // noop
+    }
+
+    /**
+     * The name of the Kamelet of a kamelet: endpoint uri, or null when it is 
not one, it is kamelet:source or
+     * kamelet:sink (the template of a Kamelet), or the name is a placeholder 
or an expression.
+     */
+    static String kameletName(String uri) {
+        if (uri == null || !uri.startsWith("kamelet:")) {
+            return null;
+        }
+        String name = 
FileUtil.stripLeadingSeparator(uri.substring("kamelet:".length()));
+        int q = name.indexOf('?');
+        if (q >= 0) {
+            name = name.substring(0, q);
+        }
+        int slash = name.indexOf('/');
+        if (slash >= 0) {
+            // kamelet:name/routeId
+            name = name.substring(0, slash);
+        }
+        if (name.isEmpty() || Kamelet.SOURCE_ID.equals(name) || 
Kamelet.SINK_ID.equals(name)
+                || name.contains("{{") || name.contains("${")) {
+            return null;
+        }
+        return name;
+    }
+
+    /**
+     * The location of the Kamelets: the location option of the endpoint, 
otherwise the one of the kamelet component.
+     */
+    private String kameletLocation(String uri) {
+        int q = uri.indexOf('?');
+        if (q >= 0) {
+            try {
+                Map<String, Object> parameters = 
URISupport.parseQuery(uri.substring(q + 1));
+                Object loc = parameters.get(Kamelet.PARAM_LOCATION);
+                if (loc != null) {
+                    return loc.toString();
+                }
+            } catch (Exception e) {
+                // use the location of the component
+            }
+        }
+        if (camelContext.getComponent("kamelet") instanceof KameletComponent 
kc) {
+            return kc.getLocation();
+        }
+        return Kamelet.DEFAULT_LOCATION;
+    }
+
+    /**
+     * The Kamelet file in the location, as the kamelet component finds it 
(RouteTemplateHelper), or null when it is not
+     * there.
+     */
+    private Resource resolveKamelet(String name, String location) {
+        if (location == null) {
+            return null;
+        }
+        ResourceLoader resourceLoader = 
PluginHelper.getResourceLoader(camelContext);
+        for (String path : location.split(",")) {
+            // using dot as current dir must be expanded into absolute path
+            if (".".equals(path) || "file:.".equals(path)) {
+                path = "file:" + FileUtil.onlyPath(new 
File(".").getAbsolutePath());
+            }
+            Resource res = null;
+            // a path with an extension is the Kamelet file itself
+            String ext = FileUtil.onlyExt(path);
+            if (ext != null && !ext.isEmpty()) {
+                res = resourceLoader.resolveResource(path);
+            }
+            if (res == null || !res.exists()) {
+                res = resourceLoader.resolveResource((path.endsWith("/") ? 
path : path + "/") + name + ".kamelet.yaml");
+            }
+            if (res != null && res.exists()) {
+                return res;
+            }
+        }
+        return null;
+    }
+
     /**
      * To automatic downloaded dependencies that Kamelets requires.
      */
diff --git 
a/dsl/camel-kamelet-main/src/test/java/org/apache/camel/main/download/DependencyDownloaderKameletTest.java
 
b/dsl/camel-kamelet-main/src/test/java/org/apache/camel/main/download/DependencyDownloaderKameletTest.java
new file mode 100644
index 000000000000..faa569d7a983
--- /dev/null
+++ 
b/dsl/camel-kamelet-main/src/test/java/org/apache/camel/main/download/DependencyDownloaderKameletTest.java
@@ -0,0 +1,143 @@
+/*
+ * 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.main.download;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.kamelet.KameletComponent;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class DependencyDownloaderKameletTest {
+
+    private static final String KAMELET = """
+            apiVersion: camel.apache.org/v1
+            kind: Kamelet
+            metadata:
+              name: my-soap-action
+            spec:
+              definition:
+                title: My SOAP action
+              dependencies:
+                - "camel:cxf-soap"
+                - "camel:kamelet"
+              template:
+                from:
+                  uri: kamelet:source
+                  steps:
+                    - log: "${body}"
+            """;
+
+    @TempDir
+    Path dir;
+
+    @Test
+    void theDependenciesOfAKameletAreDownloadedWhenARouteThatUsesItIsAdded() 
throws Exception {
+        // CAMEL-27364: the route of a Kamelet is created after the routes, so 
a doCatch on a class of a dependency of the
+        // Kamelet (org.apache.cxf.binding.soap.SoapFault for camel:cxf-soap) 
failed with ClassNotFoundException
+        Files.writeString(dir.resolve("my-soap-action.kamelet.yaml"), KAMELET);
+        RecordingDownloader downloader = new RecordingDownloader();
+        try (CamelContext context = new DefaultCamelContext()) {
+            context.addService(downloader);
+            context.getComponent("kamelet", 
KameletComponent.class).setLocation("file:" + dir);
+            context.addService(new DependencyDownloaderKamelet(context, 
"4.0.0"));
+
+            context.addRoutes(new RouteBuilder() {
+                @Override
+                public void configure() {
+                    
from("direct:start").to("kamelet:my-soap-action?address=http://localhost:8080";)
+                            
.to("kamelet:other-not-there").to("kamelet:{{name}}");
+                }
+            });
+
+            // the route is added, but not created: the dependencies of its 
Kamelet are already downloaded
+            
assertTrue(downloader.downloaded.contains("org.apache.camel:camel-cxf-soap"), 
downloader.downloaded.toString());
+            
assertFalse(downloader.downloaded.contains("org.apache.camel:camel-kamelet"), 
downloader.downloaded.toString());
+        }
+    }
+
+    @Test
+    void theNameOfTheKamelet() {
+        assertEquals("my-soap-action", 
DependencyDownloaderKamelet.kameletName("kamelet:my-soap-action"));
+        assertEquals("my-soap-action", 
DependencyDownloaderKamelet.kameletName("kamelet://my-soap-action?a=b"));
+        assertEquals("my-soap-action", 
DependencyDownloaderKamelet.kameletName("kamelet:my-soap-action/myRoute?a=b"));
+        // the template of a Kamelet, and a name only known at runtime
+        assertNull(DependencyDownloaderKamelet.kameletName("kamelet:source"));
+        assertNull(DependencyDownloaderKamelet.kameletName("kamelet:sink"));
+        
assertNull(DependencyDownloaderKamelet.kameletName("kamelet:{{name}}"));
+        
assertNull(DependencyDownloaderKamelet.kameletName("kamelet:${header.name}"));
+        assertNull(DependencyDownloaderKamelet.kameletName("direct:start"));
+        assertNull(DependencyDownloaderKamelet.kameletName(null));
+    }
+
+    /** Records the downloads, with nothing on the classpath, and downloads 
nothing. */
+    private static class RecordingDownloader extends MavenDependencyDownloader 
{
+
+        private final List<String> downloaded = new CopyOnWriteArrayList<>();
+
+        @Override
+        protected void doBuild() {
+            // noop
+        }
+
+        @Override
+        protected void doInit() {
+            // noop
+        }
+
+        @Override
+        protected void doStart() {
+            // noop
+        }
+
+        @Override
+        protected void doStop() {
+            // noop
+        }
+
+        @Override
+        public void downloadDependency(String groupId, String artifactId, 
String version) {
+            downloaded.add(groupId + ":" + artifactId);
+        }
+
+        @Override
+        public void downloadDependency(String groupId, String artifactId, 
String version, boolean transitively) {
+            downloaded.add(groupId + ":" + artifactId);
+        }
+
+        @Override
+        public boolean alreadyOnClasspath(String groupId, String artifactId, 
String version) {
+            return false;
+        }
+
+        @Override
+        public void onLoadingKamelet(String name) {
+            // noop
+        }
+    }
+}

Reply via email to