WebSphere Application Server & Liberty

Jakarta Batch Post 138: Jakarta Batch Extras - ArrayItemReader

By David Follis posted Thu May 20, 2021 08:09 AM

  
This post is part of a series delving into the details of the JSR-352 (Java Batch) specification. Each post examines a very specific part of the specification and looks at how it works and how you might use it in a real batch application.

To start at the beginning, follow the link to the first post.

The next post in the series is here.

This series is also available as a podcast on iTunesGoogle PlayStitcher, or use the link to the RSS feed
-----

We’ve been talking a lot about reading flat files in various formats and essentially you can view the whole file as an array of whatever it is you’re reading.  Whether it is CSV data or JSON or some syntax of your own, you’ve got a bunch of things that are basically the same, in a fixed-size set which is pretty much an array.  So that got me wondering what the ArrayItemReader does…

It is pretty cool because it reads an array of whatever you want to give it.  It is based on the ‘resource’ property that gets injected from the JSL.  You can point it to a file or you can just give it some inline data enclosed in square brackets (those are important – that’s how it knows it isn’t a file). 

Then the ArrayItemReader will just crack that open and start reading things from it.  By default it assumes every entry is a String and will return them to you that way.  But you can have it read some other primitive type or read some object type of your own. 

Probably the best way to understand it is to look at the examples in the prolog for the source, which I’m going to shamelessly steal and put here..

 <property name="resource" value='["a", "b", "c"]'/>

 

That array of 3 items will be read as strings and you’ll make three passes through the chunk loop.  But what if you had numbers?  Something like this:

<property name="resource" value="[1, 2, 3]"/>

<property name="beanType" value="java.lang.Integer"/>

Then the ArrayItemReader will use the beanType value to figure out these are integers and read them (and pass them to the ItemProcessor as) Integers.

Or you could have some JSON (and here I’m simplifying the example in the code):

<property name="beanType" value="org.jberet.support.io.Movie"/>

 <property name="resource" value='[

 {"rank" : 1, "title" : "Number One", "opn" : "2017-01-01"},

 {"rank" : 2, "title" : "Number Two", "opn" : "2017-02-02"}

]>

 

Here the application object (Movie) will be used to map the JSON array entries (just two here).  And if you don’t like instream data, drop the square brackets and put the data in a file:

 <property name="resource" value="movies-2012.json"/>

<property name="beanType" value="org.jberet.support.io.Movie"/>
0 comments
32 views

Permalink