Is it possible to kick off a camel route using a java interface or bean?

ScArcher2 picture ScArcher2 · Jul 29, 2010 · Viewed 25.4k times · Source

I'd like to setup a spring bean (either via interface or bean class). that I can call to "start" a Route.

In this simple example when I call sayHello("world") from code I'd like it to route the return value of the sayHello method the endpoint that will write it out to a file.

Does anyone know if this is possible, or how to go about this? I know I can expose that same interface via CXF and make this work, but I really just want to call a method, not go through the trouble of sending a jms message or calling a webservice.

public interface Hello{
   public String sayHello(String value);
}

from("bean:helloBean").to("file:/data/outbox?fileName=hello.txt");

Answer

mokshino picture mokshino · Feb 28, 2013

You can use ProducerTemplate:

import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Component
public class HelloImpl implements Hello {

    @Produce(uri = "direct:start")
    private ProducerTemplate template;

    @Override
    public Object sayHello(String value) throws ExecutionException, InterruptedException {
        Future future = template.asyncSendBody(template.getDefaultEndpoint(), value);
        return future.get();
    }
}

and your camel route should looks like:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.mycompany.camel"/>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:start"/>
            <to uri="log:com.mycompany.camel?level=DEBUG"/>
        </route>
    </camelContext>

</beans>