Sunday, 13 October 2013

Camel Transformation using Processor Example


Camel API provides Message translation using Processor , Bean and by using Transform method in DSL. In this example we will see how to create a simple router and transforming data using Processor.


Camel supports the Message Translator from the EIP patterns by using an arbitrary Processor in the routing logic, by using a beanto perform the transformation, or by using transform() in the DSL.

The Camel Processoris an interface defined in org.apache.camel. Processor with a single method

public void process(Exchange exchange) throws Exception

In this process we can directly work with Exchange object an modify/Transform whatever we want.


Transform a simple text file to csv file using Camel Processor

1.Create a Maven Project.

Create a maven project and add below dependencies for camel core


Create two end point folders inside project as source and destinations. In the source folder place below sample input text file which we are going to transform.


Hai,Welecome to Camel
This is one simple transformation

2. Create a Camel route and processor

In this class we have to implement org.apache.camel. Processor process method. In this method we will get our input data as exchange object, here we are reading the exchange object as String and transforming to CSV format and setting to exchange again.

package com.vinod.test;

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

public class CamelTransformation {
    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.addRouteBuilder(new MyTransformRoute());;

class MyTransformRoute extends RouteBuilder {
    public void configure() {
        System.out.println("My Routing Started");
        from("file:source?noop=true").process(new MyTransformProcessor()).to("file:destination?fileName=output.csv");

        System.out.println("My Routing complete");


class MyTransformProcessor implements Processor {

    public void process(Exchange exchange) throws Exception {
        System.out.println("MyProcessor started");
        String myString = exchange.getIn().getBody(String.class);
        String[] myArray = myString.split(System.getProperty("line.separator"));
        StringBuffer sb = new StringBuffer();
        for (String s : myArray) {
        System.out.println("MyProcessor complete");


3. Run it

Run the above program and we can see new output.csv file has been generated inside output folder and printing logs in the console.


Download example