Camel Data transformation using Custom Expression


Camel provides custom expression class to control the data transformation. Here is one example which will convert the text file to html format.

Example

package com.vinod.test;

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

public class CamelDatatransformation {
    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 {
        from("file:source").transform(new Expression() {
            public <T> T evaluate(Exchange exchange, Class<T> type) {
                String body = exchange.getIn().getBody(String.class);
                body = body.replaceAll("\n", "<br/>");
                body = "<html><body>" + body + "</body></html>";
                return (T) body;
            }
        }).to("file:destination");
    }
}

Run it and place one input text file in source folder and see the destination folder

Done!!!

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts