13
votes

How can I add a camel route at run-time in Java? I have found a Grails example but I have implement it in Java.

My applicationContext.xml already has some predefined static routes and I want to add some dynamic routes to it at run time. Is it possible? Because the only way to include dynamic route is to write the route.xml and then load the route definition to context. How will it work on existing static routes? Route at runtime

3

3 Answers

23
votes

you can simply call a few different APIs on the CamelContext to add routes...something like this

context.addRoutes(new MyDynamcRouteBuilder(context, "direct:foo", "mock:foo"));
....
private static final class MyDynamcRouteBuilder extends RouteBuilder {
    private final String from;
    private final String to;

    private MyDynamcRouteBuilder(CamelContext context, String from, String to) {
        super(context);
        this.from = from;
        this.to = to;
    }

    @Override
    public void configure() throws Exception {
        from(from).to(to);
    }
}

see this unit test for the complete example...

https://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/builder/AddRoutesAtRuntimeTest.java

1
votes

@Himanshu, Please take a look at dynamicroute options (in other words routing slip) that may help you dynamically route to different 'destinations' based on certain condition.

Check the dynamic router help link in camel site;

http://camel.apache.org/dynamic-router.html

from("direct:start")
    // use a bean as the dynamic router
    .dynamicRouter(method(DynamicRouterTest.class, "slip"));

And within the slip method;

/**
 * Use this method to compute dynamic where we should route next.
 *
 * @param body the message body
 * @return endpoints to go, or <tt>null</tt> to indicate the end
 */
public String slip(String body) {
    bodies.add(body);
    invoked++;

    if (invoked == 1) {
        return "mock:a";
    } else if (invoked == 2) {
        return "mock:b,mock:c";
    } else if (invoked == 3) {
        return "direct:foo";
    } else if (invoked == 4) {
        return "mock:result";
    }

    // no more so return null
    return null;
}

Hope it helps...

Thanks.

0
votes

One such solution could be:

Define route:

private RouteDefinition buildRouteDefinition() {
    RouteDefinition routeDefinition = new RouteDefinition();
    routeDefinition.from(XX).to(ZZ); // define any route you want
    return routeDefinition;
}

Get Model Context and create route:

CamelContext context = getContext();
ModelCamelContext modelContext = context.adapt(ModelCamelContext.class);
modelContext.addRouteDefinition(routeDefinition);

There are more way of getting camel context. To name few:

  • In processor, you can use exchange.getContext()
  • Through RouteBuilder reference, you can use routeBuilder.getContext()