Wednesday, June 5, 2013

JobExecution access in Camel Spring Batch

Starting from Apache Camel 2.10, our users can benefit from the Spring Batch component. Recently one of such users approached me with the question - how can I access execution context of job started by Camel.

So far the easiest way to access JobExecution instance from the Camel was to register CamelJobExecutionListener to the Spring Batch.
<batch:job>
  <batch:step>
  ...
  </batch:step>
  <batch:listeners>
    <batch:listener ref="camelJobExecutionListener"/>
  </batch:listeners>
</batch:job>

<bean id="camelJobExecutionListener"
  class="org.apache.camel.component.spring.batch.support.CamelJobExecutionListener">
  <constructor-arg ref="camelTemplate"/>
  <constructor-arg value="seda:jobExecutionEventsQueue"/>
</bean>
Example above demonstrates how to collect JobExecution instances sent to Camel before the batch job is started and after it is completed. In this particular case JobExecutions will be collected in the SEDA queue named jobExecutionEventsQueue.

Starting from the Camel 2.11.1 SpringBatchProducer will also automatically forward JobExecution instance (one returned by the JobLauncher) as the output message. You can use the obtained JobExecution reference to perform some operations using the Spring Batch API directly.
from("direct:startBatch").
  to("spring-batch:myJob").
  to("mock:JobExecutions");
...
MockEndpoint mockEndpoint = ...;
JobExecution jobExecution = 
  mockEndpoint.getExchanges().get(0).getIn().getBody(JobExecution.class);
BatchStatus currentJobStatus = jobExecution.getStatus();
I hope this tiny enhancement will improve the experience of using Spring Batch with Apache Camel. If we can do anything to make the Camel Spring Batch API more developer-friendly, just drop us a line. Camel riders are always eager to improve components API.