Search code examples
apacheheaderapache-camelmarshallingdataformat

camel custom marshalling with dataFormat name in header


I'm having two routes in two separated projects :

  1. First route is setting the header with a data format bean name as a constant :

setHeader("dataFormatBeanName", constant("myFirstList"))

First route :

public class MyTest {
    @Configuration
    public static class MyTestConfig extends CamelConfiguration {

        @Bean(name = "myFirstList")
        public DataFormat getMyFirstListDataFormat() {
            return new MyFirstListDataFormat();
        }

        @Bean(name = "mySecondList")
        public DataFormat getMySecondListDataFormat() {
            return new MySecondListDataFormat();
        }

        @Bean
        public RouteBuilder route() {
            return new RouteBuilder() {

                @Override
                public void configure() throws Exception {
                    from("direct:testFirstDataFormat").setHeader("dataFormatBeanName", constant("myFirstList")).to("direct:myRoute");
                    from("direct:testSecondDataFormat").setHeader("dataFormatBeanName", constant("mySecondList")).to("direct:myRoute");
                }
            };
        }
    }
}
  1. Second route is supposed to retrieve the bean name from the header and use it as a custom marshaller. Something like :

custom(header("dataFormatBeanName"))

(doesn't compile)

Anyone knows how I'm supposed to get my bean name from the header to use it in the custom method ?

@Component
public class MyRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        final RouteDefinition routedefinition = this.from("direct:myRoute");
        routedefinition.marshal().custom(??????????).to("netty4:tcp://{{route.address}}:{{port}}?textline=true&sync=true");
    }

Solution

  • A collegue of mine (thanks to him) found the definite solution :

    1. set bean name in the exchange properties : exchange.setProperty("myDataFormat", "myDataFormatAutowiredBean");

    2. retrieve the dataFormat bean with RecipientList pattern and (un)marshal :

    routedefinition.recipientList(simple("dataformat:${property.myDataFormat}:marshal")); routedefinition.recipientList(simple("dataformat:${property.myDataFormat}:unmarshal"));

    Very concise and works just fine.