Wednesday, 6 October 2010

jruby processor for camel with jruby1.5

Here how to wrote a camel processor in jruby. A processor is a class able to modify message exchange like adding a header, changing message or just doing log.

First of all a jruby1.5 is required.

To start a camel project launch the maven task:
mvn archetype:create -DarchetypeGroupId=org.apache.camel.archetypes -DarchetypeArtifactId=camel-archetype-java -DarchetypeVersion=2.4.0 -DgroupId=com.test -DartifactId=rubyProcessor

Move to the created rubyProcessor directory and create a custom src/main/ruby/com/test directory and place there the following:

require 'java'
java_import "org.apache.camel.Exchange"
java_import "org.apache.camel.Processor"

java_package "com.test"

class DownloadLogger
  java_signature 'DownloadLogger()'
  java_implements 'Processor'

  java_signature "void process(Exchange exchange)"
  def process(exchange)
    puts "Ruby downloaded: #{exchange.in.get_header("CamelFileName")}"
  end
end

Modify java source file at src/main/java/com/test/MyRouteBuilder.java to:
 from("file:src/data?noop=true").
     process(new it.unimore.cesia.DownloadLogger()).
            choice().
                when(xpath("/person/city = 'London'")).to("file:target/messages/uk").
                otherwise().to("file:target/messages/others");

Add to the pom.xml file the jruby dependency:
 
      org.jruby
      jruby-complete
      1.5.3
    
located with sonatype nexus service.

Now compile with jrubyc the ruby source class with:
/opt/jruby-1.5.1/bin/jrubyc --java src/main/ruby/com/test/download_logger.rb
cp -v  com/test/DownloadLogger.java src/main/java/it/com/test
The java source class is created in the com/test directory of the presente working directory: it might be wise to move to src/main/java, maybe, so the cp can be saved.

Then execute camel application with mvn camel:run.

After a while you should be seeing:
Ruby downloaded: message2.xml
Ruby downloaded: message1.xml

No comments: