Tuesday, 1 January 2019

Camel: filtering the content using message filters

You can filter the messages while sending to the destinations.

For example, below statements copy only text files from ‘demo’ folder to ‘demoCopy’ folder.

Predicate onlyTextFiles = new Predicate() {

         @Override
         public boolean matches(Exchange exchange) {
                  String fileName = (String) exchange.getIn().getHeader("CamelFileName");
                  return fileName.endsWith(".txt");
         }
        
};

from("file:C:\\Users\\Public\\demo?noop=true")
         .filter(onlyTextFiles)
              .to("file:C:\\Users\\Public\\demoCopy");


I am using below maven dependency
                  <dependency>
                           <groupId>org.apache.camel</groupId>
                           <artifactId>camel-core</artifactId>
                           <version>2.22.1</version>
                  </dependency>

Find the below working application.

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

import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.builder.RouteBuilder;

public class FileCopyRoute extends RouteBuilder {

 Predicate onlyTextFiles = new Predicate() {

  @Override
  public boolean matches(Exchange exchange) {
   String fileName = (String) exchange.getIn().getHeader("CamelFileName");
   return fileName.endsWith(".txt");
  }

 };

 @Override
 public void configure() throws Exception {
  from("file:C:\\Users\\Public\\demo?noop=true").filter(onlyTextFiles).to("file:C:\\Users\\Public\\demoCopy");
 }

}


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();
 }
}

Run Application.java, you can observe only text files are copied to destination folder.


Previous                                                 Next                                                 Home

No comments:

Post a Comment