skip to Main Content

How to set default data format for a component in Apache Camel?

I have a number of routes interacting with different ActiveMQ queues. At the moment all of them look like

from("...")
    .process(...)
    .marshal().json() // (1)
    .to("activemq:queue:...");

or

from("activemq:queue:...")
    .unmarshal().json() // (2)
    .process(...)
    .to("...");
  1. I would like to replace lines (1) and (2) with either component or context level configuration. Basically saying only once ‘message payload going through ActiveMQ has to be a JSON string’.
  2. I don’t like to add any additional routes, processors, headers, URI parameters, etc.
  3. Ideally, it would be applicable for other components and formats besides ActiveMQ and JSON

2

Answers


  1. Chosen as BEST ANSWER

    Using interceptors (Based on Claus Ibsen's comment)

    new RouteBuilder() {
        @Override
        public void configure() throws Exception {
    
            // interceptors
            interceptSendToEndpoint("activemq:queue:*")
                .marshal()
                .json();
    
            interceptFrom("activemq:queue:*")
                .unmarshal()
                .json();
    
            // routes
            from("...")
                .process(...)
                .to("activemq:queue:...");
    
            from("activemq:queue:...")
                .process(...)
                .to("...");
        }
    }
    

    Notes:

    1. interceptors have to be defined before any routes in RouteBuilder. Otherwise IllegalArgumentException is thrown explaining situation.
    2. interceptors are not shared and have to be defined in each RouteBuilder.

  2. You could marshall/unmarshall using a named reference to a data format that you can define once (here as “myDefaultFormat”) in your Camel Registry:

    from("activemq:queue:...")
    .unmarshal(myDefaultFormat)
    

    This way, you dont have to repeat .json() everywhere
    (but ok, you have yet to repeat the named reference :-$ )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search