Wednesday, 20 October 2010

My first jruby javabean

I was going to write a javabean to be used inside camel in a java route like this:

from("file:src/data?noop=true").
     beanRef("addCorrelationId").
     log("log:endRoute");

in the MyRouteBuilder.java file of a standard mvn generated camel project.

Of course the bean has to be recalled in the came-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <bean id="addCorrelationId" class="com.test.AddCorrelationId"/>

  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <package>com.test</package>
  </camelContext>

</beans>

So I created inside src/main/ruby/com/test the following file (add_correlation_id.rb):
require 'java'

java_import "org.apache.camel.Exchange"
java_import "org.apache.camel.Processor"
java_import "org.slf4j.Logger"
java_import "org.slf4j.LoggerFactory"
java_import "ch.qos.logback.classic.LoggerContext"

java_package "com.test"

class AddCorrelationId
  def initialize
    @logger = LoggerFactory.getLogger("com.test.#{__FILE__}");
    @logger.debug("Hello from #{__FILE__}.");    
  end  

#java_annotation 'Exchange'
java_signature 'void process(Exchange exchange)'
  def process(exchange)
    @logger.debug(File.open(exchange.in.body.getBody.toString).read);    
    exchange.out.set_header("JMSCorrelationId", "mytestcorrelationId")
  end

end

Please note the java_signature statement to instruct camel to bind to the process function.

According to CamelInAction it should be possible to enforce the binding of certain parameter in the process function using annotation. Unfortunately I wasn't able to.

Next one need to compile jruby to a java source class:
jruby -S jrubyc --java -t src/main/java src/main/ruby/con/test
And run the maven camel task:
mvn camel:run
You should see printed the body of the files, both on console and to the target of logback (defined in src/main/resources/logback.xml). The header adding task has no effect on a file.

In order to use the compelling logback library, I had to add to the pom.xml:
 <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>${logback-version}</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback-version}</version>
    </dependency>
    <dependency>
      <groupId>org.jruby</groupId>
      <artifactId>jruby-complete</artifactId>
      <version>1.5.3</version>
    </dependency>

No comments: