Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a Apache Camel route at runtime from a file

Tags:

apache-camel

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?

like image 648
Phil Avatar asked Nov 18 '25 02:11

Phil


1 Answers

I was able to get it to load within a RouteBuilder from a string of the yaml

package org.acme;

import org.apache.camel.CamelContext;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.Resource;
import org.apache.camel.spi.RoutesLoader;
import org.apache.camel.support.ResourceHelper;

public class MyRouteBuilder extends RouteBuilder {

    @Override
    public void configure() {
        CamelContext context = getContext();
        String myRoute = "- route:\n" +
                "    from: \"timer:yaml?period=3s\"\n" +
                "    steps:\n" +
                "      - set-body:\n" +
                "          simple: \"Timer fired ${header.CamelTimerCounter} times\"\n" +
                "      - to:\n" +
                "          uri: \"log:yaml\"\n" +
                "\n";
        try {
            ExtendedCamelContext extendedCamelContext = context.adapt(ExtendedCamelContext.class);
            RoutesLoader loader = extendedCamelContext.getRoutesLoader();
            Resource resource = ResourceHelper.fromString("any.yaml", myRoute);
            loader.loadRoutes(resource);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 179
Phil Avatar answered Nov 20 '25 04:11

Phil