Batch Applications tutorial on WildFly

This tutorial discusses about Batch Applications for the Java Platform (JSR-352) which can be used to define, implement and running batch jobs. Batch jobs are composed of a set of tasks which can be automatically executed without user interaction. These tasks are executed periodically or when resource usage is low and they often process large amounts of information such as log files, database records or images. Examples include billing, report generation, data format conversion, and image processing. These tasks are called batch jobs. The batch framework is a rather rich one as it includes a Java API an XML configuration and a batch runtime.

Batch applications are broken down in a set of steps which specify their execution order. A simple batch might include just to elaborate sequentially a set of records, however more advanced ones may specify additional elements like decision elements or parallel execution of steps.

Before diving into the example, some definitions first: what is a step? put it simply, a step is an independent and sequential phase of a batch job. A step it self can contain chunk-oriented steps and task-oriented steps.

Chunk-oriented steps process data by reading items from a source, applying some transformation/business logic to each item, and storing the results. Chunk steps operate on one item at a time and group the results into a chunk. The results are stored when the chunk reaches a configurable size. Chunk-oriented processing makes storing results more efficient and facilitates transaction demarcation.

java ee 7 batch wildfly java ee 7 batch wildfly
Task-oriented steps, on the other hand, execute actions other than processing single items from a source. A typical example of task-oriented step might be some DDL on a database or operation on a file system. In terms of comparison a chunk oriented step can be used for massive, long running tasks whilst a task oriented step might be fit for a set of batch operations that are to be executed periodically.

JSR 352 also defines a roll-your-own kind of a step called a batchlet. A batchlet is free to use anything to accomplish the step, such as sending an e-mail.

In this tutorial we will learn how to use a Chunk-oriented steps. Each chunk step is in turn broken in three parts:

  • The Read chunk part which is used to read the single items from a source of data (database/fs/ldap etc.)
  • The Processor chunk part manipulates one item at a time using the logic defined by the application. (e.g. sorting, filtering data, trasnforming data etc.)
  • The Writer chunk part is used to write the item which has been processed in the earlier phase.

java ee 7 batch wildfly java ee 7 batch wildfly

Due to its nature, chunk steps are usually long-running activities, therefore it is possible to bookmark their progress using checkpoints. A checkpoint can be used to restart the execution of a step which has been interrupted.

In this tutorial we will see a simple yet powerful example of batch job which takes as input a CSV file which is read, processed and inserted into a database. This example has been taken from A.Gupta Java EE 7 examples ( and it has been slightly modified in its configuration to use the default WildFly datasource,the WildFly Java EE 7 dependencies and the JBoss Maven plugin.

The Job file

Each Job must be named uniquely and must be placed in the META-INF/batch-jobs directory. So here’s our job definition file (myJob.xml) :

<job id="myJob" xmlns="" version="1.0">
    <step id="myStep" >
        <chunk item-count="3">
            <reader ref="myItemReader"/>
            <processor ref="myItemProcessor"/>
            <writer ref="myItemWriter"/>

This is the Job definition file which describes how many steps and chunks we are going to execute, the reference implementation for them and the size of the chunk, via the item-count attribute. Now here the three implementation follow here.

Writing the ItemReader

public class MyItemReader extends AbstractItemReader {

    private BufferedReader reader;

    public void open(Serializable checkpoint) throws Exception {
        reader = new BufferedReader(
                new InputStreamReader(

    public String readItem() {
        try {
            return reader.readLine();
        } catch (IOException ex) {
            Logger.getLogger(MyItemReader.class.getName()).log(Level.SEVERE, null, ex);
        return null;

Note that the class is annotated with the @Named annotation. Because the @Named annotation uses the default value, the Contexts and Dependency Injection (CDI) name for this bean is myItemReader.

Writing the ItemProcessor
Our SimpleItemProcessor follows a pattern similar to the pattern for myItemReader but it’s in charge to create a Person object from the CSV line of text which has been read:

public class MyItemProcessor implements ItemProcessor {
    SimpleDateFormat format = new SimpleDateFormat("M/dd/yy");

    public Person processItem(Object t) {
        System.out.println("processItem: " + t);
        StringTokenizer tokens = new StringTokenizer((String)t, ",");

        String name = tokens.nextToken();
        String date;
        try {
            date = tokens.nextToken();
        } catch (ParseException e) {
            return null;
        return new Person(name, date);

The processItem() method receives (from the batch runtime) a String object which is tokenized and used to create a Person object as output. Notice that the type of object returned by an ItemProcessor can be different from the type of object it received from ItemReader.

Writing the ItemWriter
Following here is the ItemWriter which, as we said, is in charge to persist the Item (Person) on the default Database (ExampleDS).

public class MyItemWriter extends AbstractItemWriter {
    EntityManager em;

    public void writeItems(List list) {
        System.out.println("writeItems: " + list);
        for (Object person : list) {

Starting a Batch Job from a Servlet

Note that the mere presence of a job XML file or other batch artifacts (such as ItemReader) doesn’t mean that a batch job is automatically started when the application is deployed. A batch job must be initiated explicitly, say, from a servlet or from an Enterprise JavaBeans (EJB) timer or an EJB business method.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (PrintWriter out = response.getWriter()) {
            out.println("<title>CSV-to-Database Chunk Job</title>");
            out.println("<h1>CSV-to-Database Chunk Job</h1>");
            JobOperator jo = BatchRuntime.getJobOperator();
            long jid = jo.start("myJob", new Properties());
            out.println("Job submitted: " + jid + "<br>");
            out.println("<br><br>Check server.log for output, also look at \"myJob.xml\" for Job XML.");
        } catch (JobStartException | JobSecurityException ex) {
            Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);

The first step is to obtain an instance of JobOperator. This can be done by calling the following:

JobOperator jo = BatchRuntime.getJobOperator(); 

The servlet then creates a Properties object and stores the input file name in it. Finally, a new batch job is started by calling the following:

jor.start("myJob", new Properties()) 

The jobname is nothing but the job JSL XML file name (minus the .xml extension). The properties parameter serves to pass any input data to the job.

The batch runtime assigns a unique ID, called the execution ID, to identify each execution of a job whether it is a freshly submitted job or a restarted job. Many of the JobOperator methods take the execution ID as parameter. Using the execution ID, a program can obtain the current (and past) execution status and other statistics about the job. The JobOperator.start() method returns the execution ID of the job that was started.

Compiling the Batch Code

In order to compile your project, I’ve changed the original pom.xml for this project by including the org.jboss.spec.javax.batch dependency. Note also that I’m using the new jboss-javaee-7.0 BOM while, as far as I know, the jboss-javaee-7.0-with-hibernate bom is still not available.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
   <name>Batch Applications for the Java Platform (JSR-352) Example</name>
   <description>Batch Applications for the Java Platform (JSR-352) Example</description>
         <name>Apache License, Version 2.0</name>
      <!-- maven-compiler-plugin -->
      <!-- Import the Batch API which is included in WildFly 8 -->
      <!-- Import the CDI API -->
      <!-- Import the Common Annotations API (JSR-250) -->
      <!-- Import the Servlet API -->
      <!-- Set the name of the war, used as the context root when the app is deployed -->
               <!-- Java EE 6 doesn't require web.xml, Maven needs to catch up! -->
         <!-- JBoss AS plugin to deploy war -->
         <!-- Compiler plugin enforces Java 1.6 compatibility and activates 
                annotation processors -->

Download the Maven project for this example from