Saturday 29 December 2018

Apache Camel: Content based routing

In this post, I am going to explain, how can you perform content based routing. Here the content can be anything like data headers, file name, content of the file, file modification date etc.,

Create new maven project ‘camelContentRouting’ in eclipse. If you do not know, how to create maven project, refer my previous tutorials.

Camel provides number predicates to route the information based on given condition.

from("file:C:\\Users\\Public\\demo?noop=true")
.choice()
.when(header("CamelFileName")
.endsWith("xlsx"))
.to("file:C:\\Users\\Public\\demoCopyXlsFiles");

Above snippet copy all xls file to ‘demoCopyXlsFiles’ folder.

Project structure looks like below.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>camelContentRouting</groupId>
  <artifactId>camelContentRouting</artifactId>
  <version>1</version>
  
   <dependencies>
  <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-core -->
  <dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-core</artifactId>
   <version>2.22.1</version>
  </dependency>

 </dependencies>
</project>


FileCopyRoute.java
package com.sample.app.routes;

import org.apache.camel.builder.RouteBuilder;

public class FileCopyRoute extends RouteBuilder {

 @Override
 public void configure() throws Exception {
  from("file:C:\\Users\\Public\\demo?noop=true").choice().when(header("CamelFileName").endsWith("xlsx"))
    .to("file:C:\\Users\\Public\\demoCopyXlsFiles");
 }

}

Application.java

package com.sample.app;

import java.util.concurrent.TimeUnit;

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

import com.sample.app.routes.FileCopyRoute;

public class Application {
 public static void main(String args[]) throws Exception {
  CamelContext context = new DefaultCamelContext();

  context.addRoutes(new FileCopyRoute());

  context.start();

  TimeUnit.MINUTES.sleep(1);

  context.stop();
 }
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment