Search code examples
apache-camel

Load a Apache Camel route at runtime from a file


I am attempting to load an Apache Camel route at runtime from a file. This means

My "route.yaml" file is as follows.

- route:
    from: "timer:yaml?period=3s"
    steps:
      - set-body:
          simple: "Timer fired ${header.CamelTimerCounter} times"
      - to:
          uri: "log:yaml"

I have seen that in the past it was possible to do the following to load a route xml file, but now this cannot be done. For example I see loadRoutesDefinition at Unable to start Camel Routes which are loaded from external XML

InputStream routesXml = new ByteArrayInputStream(routePropertyValue.toString().getBytes());
RoutesDefinition loadedRoutes = camelContext.loadRoutesDefinition(routesXml);
camelContext.addRouteDefinitions(loadedRoutes.getRoutes());

How to do it with the current Apache Camel?


Solution

  • You can also load an XML file from classpath.

    import org.apache.camel.CamelContext;
    import org.apache.camel.CamelContextAware;
    import org.apache.camel.ExtendedCamelContext;
    import org.apache.camel.impl.engine.DefaultResourceResolvers;
    import org.apache.camel.spi.Resource;
    import org.apache.camel.spi.RoutesLoader;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    @Component
    public class RouteLoader implements CamelContextAware {
    
      private CamelContext camelContext;
    
      @Override
      public CamelContext getCamelContext() {
        return camelContext;
      }
    
      @Override
      public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
      }
    
      @PostConstruct
      void loadRoutes() {
        loadRoute("camel-routes.xml");
      }
    
      private void loadRoute(String name) {
        ExtendedCamelContext extendedCamelContext = camelContext.adapt(ExtendedCamelContext.class);
        RoutesLoader loader = extendedCamelContext.getRoutesLoader();
        try (DefaultResourceResolvers.ClasspathResolver resolver = new DefaultResourceResolvers.ClasspathResolver()) {
          resolver.setCamelContext(camelContext);
          Resource resource = resolver.resolve("classpath:" + name);
          loader.loadRoutes(resource);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    
    }