Search code examples
javaapache-camel

Camel REST Bean Chaining


I currently have a REST route builder that looks as follows:

rest("/v1")
  .post("/create")
    .to("bean:myAssembler?method=assemble(${in.header.content})")
    .to("bean:myService?method=create(?)");

The bean myAssembler takes raw JSON and transforms this into MyObject. This object is then returned and I want it forwarded onto myService as a parameter for its create method.

How can I do this using Camel?


Solution

  • Your beans will bind automatically to specific parameters like Exchange if you put it as a parameter to a method (see complete list Parameter binding).

    One solution would be to define your route and beans like this:

    restConfiguration()
    .component("restlet")
    .bindingMode(RestBindingMode.json)
    .skipBindingOnErrorCode(false)
    .port(port);    
    
    rest("/v1")
        .post("/create")
            .route()
                .to("bean:myAssembler?method=assemble")
                .to("bean:myService?method=create");
    

    with beans like this

    public class MyAssembler {
        public void assemble(Exchange exchange) {
          String content = exchange.getIn().getHeader("content", String.class);
          // Create MyObject here.
          MyObject object; // ...transformation here.
          exchange.getOut().setBody(object);
       }
    }
    

    and this

    public class MyService {
        public void create(MyObject body) {
            // Do what ever you want with the content.
            // Here it's just log.
            LOG.info("MyObject is: " + body.toString());
         }
    }
    

    The dependencies for shown configuration are

    org.apache.camel/camel-core/2.15.3
    org.apache.camel/camel-spring/2.15.3
    org.apache.camel/camel-restlet/2.15.3
    javax.servlet/javax.servlet-api/3.1.0
    org.apache.camel/camel-jackson/2.15.3
    org.apache.camel/camel-xmljson/2.15.3
    xom/xom/1.2.5