Camel

Using a Camel Processor to modify the message

The Camel Processor is a key building block of Camel, and gives you full access to the message being transferred including the message body, any headers, and any properties associated with the message. By creating a Processor you can modify any of those elements, for example you can alter the body of the message transforming it from XML to CSV or you can add custom properties or headers to it. Let's see how to build a custom Processor which transforms the body of a Message.

camel processor

In the following class, we are creating a custom Processor named myProcessor which receives as input the files contained in /var/data/in and format them as CSV files. The files are then transferred to /vr/data/out :

package com.sample;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class ProcessorExample {

    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.enableHangupSupport();
        main.addRouteBuilder(new MyRoute());
        main.run(args);
    }
}

class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        System.out.println("My Routing Started");
        from("file:/var/data/in?noop=true").process(new MyProcessor()).to(
                "file:/var/data/out");
        System.out.println("My Routing complete");
    }
}

And here is the implementation of MyProcessor:

package com.sample;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
 
public class MyProcessor implements Processor {

    public void process(Exchange exchange) throws Exception {

        String myString = exchange.getIn().getBody(String.class);
        String[] myArray = myString.split(System.getProperty("line.separator"));
        StringBuffer sb = new StringBuffer();
        for (String s : myArray) {
            sb.append(s).append(",");
        }
        System.out.println("MyProcessor complete");
        exchange.getIn().setBody(sb.toString());
    }

    public MyProcessor() {
    }

}

On the other hand, if you prefer using Spring DSL, then you can achieve the same result using the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/bean">
   <bean id="myProcessor" class="com.sample.MyProcessor" />
   <camelContext xmlns="http://camel.apache.org/schema/spring">
      <route>
         <from uri="file:source?noop=true" />
         <process ref="myProcessor" />
         <to uri="file:dest?fileName=output.csv" />
      </route>
   </camelContext>
</beans>

0
0
0
s2smodern

Follow us on Twitter