Camel Lesson 2: Simple Transformation

Camel provides many ways for data transformation. In this tutorial we will cover a simple example of data transformation by replacing the content of one file and writing a new file as result.

Data transformation in Camel is a broad term that covers two types of transformation:

  • Data format transformation: which means that the message body is transformed from one form to another. For example, a  JSON Text file is formatted as CSV.
  • Data type transformation: which means that the data type of the message body is transformed from one type to another. For example a  java.lang.String is transformed into a JMS Message

Let's see a simple example of the first type (Data format transformation):

package com.sample;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class SimpleTransform {

	public static void main(String args[]) throws Exception {
		CamelContext context = new DefaultCamelContext();
		context.addRoutes(new RouteBuilder() {
			public void configure() {
				from("file:C:\\camel\\in\\").process(new SimpleProcessor())
				.to("file:C:\\camel\\out\\");
			}
		});
		context.start();
		Thread.sleep(10000);
		context.stop();
	}

}

Within this simple Route, we are copying files from the folder C:\camel\in into the folder C:\camel\out and transforming the content using the SimpleProcessor class which follows here:

package com.sample;

import java.util.StringTokenizer;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class SimpleProcessor implements Processor {
	public void process(Exchange exchange) throws Exception {
		String custom = exchange.getIn().getBody(String.class);
 	
		StringTokenizer st = new StringTokenizer(custom," ");
		StringBuilder csv = new StringBuilder();
		csv.append(custom.replaceAll("\n", "<br/>"));
	 
		exchange.getIn().setBody(csv.toString());
	}
}

 The SimpleProcessor class, which implements org.apache.camel.Processor is merely replacing the carriage return ("\n") with an HTML equivalent ("<br/").

camel tutorial

The Camel  Exchange interface defines two methods for retrieving messages:  getIn and getOut . The  getIn method returns the incoming message, and the  getOut method accesses the outbound message.

Using the Transform method of Java DSL

You can also use the Transform() method of the Java  DSL to transform messages. By allowing the use of expressions,  transform() permits great flexibility, and using expressions directly within the  DSL can sometimes save time. 

Let’s see the equivalent Route built using the Transform pattern: 

CamelContext context = new DefaultCamelContext();
		context.addRoutes(new RouteBuilder() {
			public void configure() {
				from("file:D:\\camel\\in\\").transform(body().regexReplaceAll("\n", "<br/>"))
				.to("file:D:\\camel\\out\\");
			}
		});

Advertisement

Cookie Alert