Batch processing in JEE7 (JSR 352)

A new feature in JEE7 is Batch Processing, an implementation of JSR 352 based on the programming model of Spring Batch. With batch processing, we understand the execution of a series of jobs (steps) , sequential or in parallel, without any user interaction. In this blog, we want to give a small overview of the capabilities of this new feature.
The code of this blog can be downloaded from here.
The zip file contains an Eclipse maven project in the folder JobAPI, and a jobapi.war file that can be deployed and tested.

The JSR 352 specification defines 2 different approaches to set up a batch, which can be combined :

The ‘chunk’ approach

This approach implements a common ETL pattern of read/process/write. A chunk is a set of data, a number of items, that is written in one ‘transaction’. So a chunk of 3 items, gives you the following execution :

  1. read item 1
  2. process item 1
  3. read item item 2
  4. process record 2
  5. read item item 3
  6. process record 3
  7. write items 1, 2, 3
  8. start reading item 4, etc…

The ‘batchlet’ approach

This approach gives you the freedom to do as you like. It’s just a piece of code, executed as part of a batch job.

The Code

For this example, I have used GlassFish 4.0 from here (no Eclipse plugin yet for the 4.1). Download the full EE, and not the Web-profile, as that one only contains a subset of the JEE7 spec. More info about the differences between these two can be found here.

As the batch process runs in background, System.out.println is used for the output. If you’re using the GlassFish plugin in Eclipse, you’ll see the output in the console view. Otherwise, check the server.log in the dir : ../glassfish4.0/glassfish/domains/domain1/logs/server.log

In the example we generate a list of 10 Data objects in the reader. A Data object contains 2 operands and the result of a calculation of those 2 that was computed in the processor. The writer prints out the result.
Let’s go over our different classes :

The object (just a value object)

public class Data {
	private Integer num1;
	private Integer num2;
	private Integer result;

	public Data(Integer num1, Integer num2) {
		this.num1 = num1;
		this.num2 = num2;
	public String toString() {
		return num1+" en "+num2+(result != null ? " = "+result : "");
	public Integer getResult() {
		return result;
	public void setResult(Integer result) {
		this.result = result;
	public Integer getNum1() {
		return num1;
	public Integer getNum2() {
		return num2;

The flow of a batch job is defined in a job xml, that is placed under the /META-INF/batch-jobs directory. We called ours : myJob.xml
As all classes are CDI beans with default names (@Named annotated), we refer to them with their lowerCamelCase name. (don’t forget to add an empty beans.xml file in the WEB-INF dir.)
We define 2 steps: the first one uses the chunked approach, executing the batch in chunks of 3 items; the second step uses the batchlet approach. This batchlet will just print a message.
Note the “next” attribute in the step, declaring what the next step will be after “step1”.

<job id="myJob" xmlns="" version="1.0" >
	<step id="step1" next="step2">
		<chunk item-count="3">
 			<reader ref="myItemReader"/>
 			<processor ref="myItemProcessorPlus"/>
 			<writer ref="myItemWriter"/>
	<step id="step2">
		<batchlet ref="myBatchlet"/>

MyItemReader : open method is executed once and creates a list. ReadItem method reads 1 item.

public class MyItemReader extends AbstractItemReader{
	private List<Data> listData = new ArrayList<Data>();
	int count=0;

	public void open(Serializable c) throws Exception {
		System.out.println("FILL LIST");
		 Random randomGenerator = new Random();
		    for (int idx = 1; idx <= 10; ++idx){
		      int randomInt1 = randomGenerator.nextInt(100);
		      int randomInt2 = randomGenerator.nextInt(100);
		      listData.add(new Data(randomInt1,randomInt2));

	public Data readItem() throws Exception {
		try {
			Data data = listData.get(count++);
			System.out.println(Thread.currentThread().getId()+" | READ  "+data);
			return data;
		} catch (IndexOutOfBoundsException e) {
			// finished
			return null;

MyItemProcessorPlus : processes 1 item : calculates the sum and puts it in the result.

public class MyItemProcessorPlus implements ItemProcessor {

	public Data processItem(Object arg0) throws Exception {
		Data data = (Data)arg0;
		System.out.println(Thread.currentThread().getId()+" | PROCESSING PLUS data: "+data.toString());
		return data;

MyItemWriter : writes a chunk of items, in our case, just prints it.

public class MyItemWriter extends AbstractItemWriter{
	List<Data> resultList = new ArrayList<Data>();
	public void writeItems(List<Object> arg0) throws Exception {
		System.out.println(Thread.currentThread().getId()+" | start write "+arg0.size()+" elements");
		for (Object o : arg0) {
			Data data = (Data)o;
			System.out.println(Thread.currentThread().getId()+" | WRITE  "+data.toString()  );
		System.out.println(Thread.currentThread().getId()+" | end write ");

MyBatchlet : second step, runs after all the chunks have been written.

public class MyBatchlet extends AbstractBatchlet {
	public String process() throws Exception {
		System.out.println("BATCHLET : Processing something else in this batchlet....");
		return null;

Now that we have our classes, we create a servlet to start the batch.
“myJob” in the start method of the JobOperator refers to the name of the batch xml file in the META-INF directory.
When the method is executed, the batch will be started in the background, and the servlet continues.

public class RunBatch extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws javax.servlet.ServletException , {
		JobOperator jo = BatchRuntime.getJobOperator();
		jo.start("myJob", null);
		resp.getWriter().println("Job started, check console for output.");

Now when we deploy our war file, and go to http://localhost:8080/jobapi/myRun, it will give the message “Job started, check console for output.” on the screen, but you can still see the output of the batch in the console/server.log :

Info: 175 | READ 42 en 80
Info: 175 | PROCESSING PLUS data: 42 en 80 = 122
Info: 175 | READ 47 en 41
Info: 175 | PROCESSING PLUS data: 47 en 41 = 88
Info: 175 | READ 74 en 6
Info: 175 | PROCESSING PLUS data: 74 en 6 = 80
Info: 175 | start write 3 elements
Info: 175 | WRITE 42 en 80 = 122
Info: 175 | WRITE 47 en 41 = 88
Info: 175 | WRITE 74 en 6 = 80
Info: 175 | end write
Info: 175 | READ 70 en 79
Info: 175 | PROCESSING PLUS data: 70 en 79 = 149
Info: 175 | READ 67 en 35
Info: 175 | PROCESSING PLUS data: 67 en 35 = 102
Info: 175 | READ 13 en 81
Info: 175 | PROCESSING PLUS data: 13 en 81 = 94
Info: 175 | start write 3 elements
Info: 175 | WRITE 70 en 79 = 149
Info: 175 | WRITE 67 en 35 = 102
Info: 175 | WRITE 13 en 81 = 94
Info: 175 | end write
Info: 175 | READ 89 en 89
Info: 175 | PROCESSING PLUS data: 89 en 89 = 178
Info: 175 | READ 24 en 29
Info: 175 | PROCESSING PLUS data: 24 en 29 = 53
Info: 175 | READ 20 en 18
Info: 175 | PROCESSING PLUS data: 20 en 18 = 38
Info: 175 | start write 3 elements
Info: 175 | WRITE 89 en 89 = 178
Info: 175 | WRITE 24 en 29 = 53
Info: 175 | WRITE 20 en 18 = 38
Info: 175 | end write
Info: 175 | READ 28 en 2
Info: 175 | PROCESSING PLUS data: 28 en 2 = 30
Info: 175 | start write 1 elements
Info: 175 | WRITE 28 en 2 = 30
Info: 175 | end write
Info: BATCHLET : Processing something else in this batchlet….

As you can see, there are 3x calls to read and process, and then 1 call to write, for every chunk of data.
When all 10 Data objects have been processed, the next step – the batchlet – is executed.

Parallel processing

The batch framework contains 2 techniques for processing data in parallel, in 2 or more separate threads. One of them is partitioning, where, for a set of data, you define which parts will be processed in the same step, but in multiple instances, in different threads. This partition definition is done in the reader. We won’t go into detail here.
A second technique can be used to define steps that will run in parallel, before continuing with the next step.

Let’s update our example for this last one. Suppose that we want a second list of data, where we compute the product iso the sum. We will create a new processor for that.

MyItemProcessorMultiply : process 1 item : calculates the product and put’s it in the result.

public class MyItemProcessorMultiply implements ItemProcessor {
	public Data processItem(Object arg0) throws Exception {
		Data data = (Data)arg0;
		System.out.println(Thread.currentThread().getId()+" | PROCESSING MULTIPLY data: "+data.toString());
		return data;

Now, in order to use this processor we need to add an extra step to our myJob.xml: use the tag “split” to indicate which steps need to run in parallel. To demonstrate the difference, the product batch wil run in chunks of 5, whereas the sum runs in chunks of 3.

<job id="myJob" xmlns="" version="1.0" >
	<split id="split1" next="step3">
		<flow id="flow1">
			<step id="step1">
				<chunk item-count="3">
		 			<reader ref="myItemReader"/>
		 			<processor ref="myItemProcessorPlus"/>
		 			<writer ref="myItemWriter"/>
 		<flow id="flow2">
			<step id="step2">
				<chunk item-count="5">
		 			<reader ref="myItemReader"/>
		 			<processor ref="myItemProcessorMultiply"/>
		 			<writer ref="myItemWriter"/>
	<step id="step3">
		<batchlet ref="myBatchlet"/>

Running our servlet will result in following output :

Info: 231 | READ 27 en 72
Info: 230 | READ 55 en 72
Info: 231 | PROCESSING MULTIPLY data: 27 en 72 = 1944
Info: 231 | READ 44 en 53
Info: 231 | PROCESSING MULTIPLY data: 44 en 53 = 2332
Info: 231 | READ 31 en 14
Info: 231 | PROCESSING MULTIPLY data: 31 en 14 = 434
Info: 230 | PROCESSING PLUS data: 55 en 72 = 127
Info: 231 | READ 87 en 84
Info: 230 | READ 3 en 8
Info: 231 | PROCESSING MULTIPLY data: 87 en 84 = 7308
Info: 230 | PROCESSING PLUS data: 3 en 8 = 11
Info: 231 | READ 31 en 1
Info: 230 | READ 63 en 28
Info: 231 | PROCESSING MULTIPLY data: 31 en 1 = 31
Info: 230 | PROCESSING PLUS data: 63 en 28 = 91
Info: 230 | start write 3 elements
Info: 231 | start write 5 elements
Info: 231 | WRITE 27 en 72 = 1944
Info: 231 | WRITE 44 en 53 = 2332
Info: 231 | WRITE 31 en 14 = 434
Info: 231 | WRITE 87 en 84 = 7308
Info: 231 | WRITE 31 en 1 = 31
Info: 230 | WRITE 55 en 72 = 127
Info: 230 | WRITE 3 en 8 = 11
Info: 230 | WRITE 63 en 28 = 91
Info: 230 | end write
Info: 231 | end write
Info: 230 | READ 30 en 90
Info: 230 | PROCESSING PLUS data: 30 en 90 = 120
Info: 230 | READ 39 en 71
Info: 230 | PROCESSING PLUS data: 39 en 71 = 110
Info: 230 | READ 48 en 23
Info: 231 | READ 51 en 36
Info: 230 | PROCESSING PLUS data: 48 en 23 = 71
Info: 231 | PROCESSING MULTIPLY data: 51 en 36 = 1836
Info: 231 | READ 49 en 30
Info: 230 | start write 3 elements
Info: 231 | PROCESSING MULTIPLY data: 49 en 30 = 1470
Info: 230 | WRITE 30 en 90 = 120
Info: 230 | WRITE 39 en 71 = 110
Info: 231 | READ 82 en 80
Info: 230 | WRITE 48 en 23 = 71
Info: 230 | end write
Info: 231 | PROCESSING MULTIPLY data: 82 en 80 = 6560
Info: 231 | READ 26 en 87
Info: 231 | PROCESSING MULTIPLY data: 26 en 87 = 2262
Info: 231 | READ 49 en 69
Info: 231 | PROCESSING MULTIPLY data: 49 en 69 = 3381
Info: 231 | start write 5 elements
Info: 231 | WRITE 51 en 36 = 1836
Info: 231 | WRITE 49 en 30 = 1470
Info: 231 | WRITE 82 en 80 = 6560
Info: 231 | WRITE 26 en 87 = 2262
Info: 231 | WRITE 49 en 69 = 3381
Info: 231 | end write
Info: 230 | READ 26 en 15
Info: 230 | PROCESSING PLUS data: 26 en 15 = 41
Info: 230 | READ 53 en 31
Info: 230 | PROCESSING PLUS data: 53 en 31 = 84
Info: 230 | READ 99 en 60
Info: 230 | PROCESSING PLUS data: 99 en 60 = 159
Info: 230 | start write 3 elements
Info: 230 | WRITE 26 en 15 = 41
Info: 230 | WRITE 53 en 31 = 84
Info: 230 | WRITE 99 en 60 = 159
Info: 230 | end write
Info: 230 | READ 54 en 91
Info: 230 | PROCESSING PLUS data: 54 en 91 = 145
Info: 230 | start write 1 elements
Info: 230 | WRITE 54 en 91 = 145
Info: 230 | end write
Info: BATCHLET : Processing something else in this batchlet….

You can see there are now 2 thread IDs : 230 and 231, one for each step.

This was just an introduction of how a batch can be set up in JEE7.
But there are many other usefull features not demonstrated in this blog.

Exception handling

  • You can continue reading/processing/writing after a configured exception is thrown during the run.
  • Configure how many times a certain exception can be thrown, before the batch is aborted.


You can write listeners that are executed

  • before/after an item is read/processed/written.
  • when a skippable exception is thrown in the reader/processor/writer
  • when a retry of a reader/processor/writer is executed


Add custom checkpoint from where to restart the batch when it was aborted.


The new Batch API gives us a lot of possibilities for setting up a batch in an EE environment. The biggest advantage is probably that it works seamlessly together with all the other EE components in our projects.

For instance, you can use your REST/WS clients to read data, your EJB’s and JPA entities to process the data, your JMS to write results to your queues, etc…

If you’re going to use this batch API, I hope you will share your experiences here, on this blog !



Java 8 Lambda : the very basics

Functional interface

In many cases – when talking about Java 8 – lambda-functions are the first thing that comes up. I found it a concept hard to grasp, as it slightly changes the way you think about coding. In this blog, I would like to show you some very simple examples, and explain what is what in the lambda world.

In versions prior to Java 8, we had SAM interfaces : Single Abstract Method-interfaces. In Java 8, the concept of SAM-interfaces has been re-created and called “functional interfaces”. These interfaces can be used in lambda-expressions. Here’s a definition of such an interface that we will be using in the examples.

interface MyCalculator {
	public double calculate(double val1, double val2);

The “FunctionalInterface” annotation is used to generate compiler level errors, when the interface is not a functional interface. A functional interface is an interface with 1 abstract method. The annotation is not required, but improves the readability of your code.

Using the lambda

When the functional interface is created, you can declare a variable to be assigned with a lambda-expression.

MyCalculator multiply = (value1, value2) -> value1 * value2;
MyCalculator sum = (value1, value2) -> value1 + value2;
System.out.println(“multiply = “+multiply.calculate(5,6));
System.out.println(“sum = “+sum.calculate(5,6));

Generates following output:
multiply = 30.0
sum = 11.0

So if you are wondering what is what in a lambda-expression :
Before the arrow = variables of your function
After the arrow = code to be executed by the abstract method of the functional interface

If we would do this the ‘old-school’ way, our code would look like this :

MyCalculator multiply = new MyCalculator() {
	public double calculate(double val1, double val2) {
					return val1 * val2;
MyCalculator sum = new MyCalculator() {
	public double calculate(double val1, double val2) {
					return val1 + val2;
System.out.println("multiply = "+multiply.calculate(5,6));
System.out.println("sum = "+sum.calculate(5,6));

The advantage of lambda is pretty clear : less code, better readability.

If you want to define more than 1 line of code, write it like this :

MyCalculator calc = (value1, value2) -> {
			System.out.println("Before calculating");
			double result = value1* value2* 3;
			System.out.println("After calculating");
			return result;
System.out.println(calc.calculate(3, 4));

Generates the following output:
Before calculating
After calculating

Use of non-local variables in lambda expressions

In versions prior to Java 8, the following code :

Calendar cal = Calendar.getInstance();
MyCalculator sum = new MyCalculator() {
	public double calculate(double val1, double val2) {
		return val1 + val2;

would generate an error :
“Cannot refer to the non-final local variable cal defined in an enclosing Scope”
on statement

because the variable “cal” was not defined as final.

The Java 8 compiler has a new capability that will convert non-local variables, used in lambda-expressions and anonymous inner class methods, automatically to final.
So in Java 8, this code will actually compile. Even better: now, we can write the previous code as a lambda-expression :

Calendar cal = Calendar.getInstance();
MyCalculator sum2 = (value1,value2) -> {
			return value1+value2;

Streams API and lambdas

New in Java 8 is the Stream API ( According to Oracle’s documentation : “A stream is not a data structure that stores elements; instead, it transports elements from a source (data structure, array, generator function, or an I/O channel), through a pipeline of computational operations.”

This is where the lambdas make their entrance, as a pipeline is a sequence of lambda expressions that can process or interrogate every element in the stream. In short : by using streams and lambda’s, we can execute a whole bunch of operations on a Collection, all in 1 statement.

Suppose we want to print out every even number from a list of Integers.

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> evenList = -> value%2==0).collect(Collectors.toList()); -> System.out.println(value));

In the second line, the filter method will return the values matching the predicate, in this case, a lambda-expression. The collect method will return the result list.
On the third line, we use a stream to print out every value of our new list, containing the even values.

If you had to write the above code in Java 7, you would need more code, so more possible flaws, less readability.
But there is more :

Map<Person.Sex, List<Person>> byGender =;

In 1 line of code, from a list of person objects, we create a map with the gender as the key.

Read the Java Doc on java.util.streams, and you’ll discover a whole new way of writing code, including parallel processing of your stream. Also, check out the Collectors API where you can find methods to convert your collections into other sorts of collections, without any for loops, etc…

The better you understand lambdas and streams, the more you’ll understand why they are such a hot issue in the Java world, the more you’ll improve your code!

JEE : Using EJB and Context annotations in a JAX-RS Provider class

A lot of new annotations have been introduced since the JEE6 spec. Before we had EJBs and servlets to cover most of our server-side objects in a JEE application. But in JEE6, CDI and JAX-RS have been added, along with a few other JSRs that are implemented using annotations. This results in a long list of annotations, where – in my opinion – it is not always clear which one to use, nor to understand how they work together.

In this blog, I would like to show you how EJB and CDI work or don’t work together, in combination with a JAX-RS Resource.

JAX-RS is used for writing REST-services. It allows you to create these services, simply by annotating a Java class.

This is our REST service class aka “resource class”. It will create a REST service on the /test url, an it returns a String. Here, for test purposes, we always generate a RuntimeException.

public class TestResource {
public String getCustomer() {
if (1==1) throw new RuntimeException("Whoops, something goes wrong");

return "Customer ABC";

Because we don’t want to send a stack trace to the client, but a meaningful response in the form of an Error class, we use a provider class and annotate it with @Provider ( This annotation is part of the JAX-RS spec.

Annotating a class with @Provider – according to the API-documentation – “marks an implementation of an extension interface that should be discoverable by JAX-RS runtime during a provider scanning phase.”

Our provider class will catch any exception thrown by the resource class, and send a proper response object to the client instead.

The returned Error class, that will be marshalled to an xml object and returned to the client :


public class Error {
private String desc;
public Error() {

public Error(String desc) {
this.desc = desc;

public String getDesc() {
return desc;

public void setDesc(String desc) {
this.desc = desc;


The provider class that will catch any exception and return the error class looks like :


public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

public Response toResponse(Exception ex) {
return Response.status(500).entity(new Error("Error during call with method : "+httpRequest.getMethod())).build();



As you can, see, we use the @Context annotation to access the current http request. When an exception is thrown by the resource class, it will automatically be handled by the toResponse method of our provider class. It returns a response, containing the Error class, that will be sent to the client in xml format. This is done by the JAX-RS framework.

Now we have an EJB bean that we want to use in order to log this error to a database, before sending the response. So we will add this to the provider class as follows :



public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

@EJB ErrorEJB errorEJB;

public Response toResponse(Exception ex) {
// log the error to the database
// return the response
return Response.status(500)
.entity(new Error("Error during call with method : "+httpRequest.getMethod()))

We made the GenericExceptionMapper a stateless bean using @Stateless, in order to be able to inject the ErrorEJB into the provider.

But now, we will get a NullPointerException on the httpRequest.getMethod, as the @Context annotation won’t work  anymore.

This is because, before our update, we only used the @Provider annotation , so this class was a CDI bean. With CDI, the container looks up the injected classes in a “scope”, which will basically be a hashmap that exists for a specific period of time :

  • @RequestScoped : per request
  • @SessionScoped : per HTTP session
  • @ApplicationScoped : per application

Into that environment we can inject the HttpServletRequest using the @Context annotation

By adding the @Statefull annotation, we made an EJB from our CDI bean.

With EJBs, the container looks also into a hashmap, but checks if the bean is of type @Stateful, @Stateless or @Singleton. So it isn’t aware of any http context.

In order to solve this problem, we will inject the our ErrorEJB as CDI bean iso an EJB.

This can be done as follows :

  • replace the @Stateless by @RequestScoped
  • replace @EJB by @Inject
  • adding an empty beans.xml file to the WEB-INF

Which gives us :



public class GenericExceptionMapper implements ExceptionMapper<Exception> {

@Context HttpServletRequest httpRequest;

@Inject ErrorEJB errorEJB;

public Response toResponse(Exception ex) {


return Response.status(500)
.entity(new Error("Error during call with method : "+httpRequest.getMethod()))


Now for JEE7, there are even more annotations available, so make sure to check the docs before using them.

A JavaFX 8 Stock Ticker application

Since Java SE 7, update 6 , JavaFX is part of the Java SE, it is officially replacing Swing as Oracle’s UI library for Java, and it runs on (any) desktop, mobile, and within the browser (applet). Java SE 7 includes version JavaFX 2.2, Java SE 8 includes JavaFX8, i.e. the version we will use here.

In this blog, I would like to demonstrate how to create a simple stock ticker, written in JavaFX. Data will be fetched by calling a REST service from
The url for the REST service returning the stockprice :

Where ‘GE’ is the symbol of the company.

Let’s start with some Eclipse setup first.

  1. install the e(fx)clipse plugin from following update site :
  2. install the Scene Builder that will be used to design the screen. The Scene Builder is a piece of software that will help you create *.FXML files. These are plain xml files that contain the layout of your screen. is the one I used
    but newer versions can be downloaded from
  3. Install a JDK SE 8

So now we are ready to go. Open Eclipse and select ‘File’ -> ‘New’ -> ‘JavaFX Project’


Enter a project name: StockTicker, set the JRE to a Java 8 install, and click finish.


A JavaFX project is created with a class. Right click the project , select Run As , Java Application, and you will see an empty window popping up. This shows that all components were correctly installed.

Our application contains a screen with a combo box, where we can select a company. After selection it will be added to a list view, where we can see its stock price update every 3 seconds. (If there is any trading activity of course : for more detail see )

The Layout

In JavaFX we can create our UI in plain Java code or using .FXML files. We’ll use the latter here, as it creates a clean separation between the view and the model.

Right click the project -> New -> Other -> Package. Then enter the popup as shown below and click finish :


Then right click the package -> New -> Other -> New FXML Document


Click Next, enter ‘MainUI’ in the name of the fxml file.
Leave the Root Element as BorderPane. This is a layout with 5 areas : top,bottom, left and right. Click finish.


A MainUI.fxml file is created. Replace the content by the following :

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane prefHeight="500.0" prefWidth="500.0" xmlns="" xmlns:fx="">
      <Label text="Stock Ticker BATS Exchange" textAlignment="CENTER" BorderPane.alignment="CENTER">
            <Font name="Arial" size="33.0" />
      <VBox BorderPane.alignment="CENTER">
            <ComboBox fx:id="cbQuote" prefHeight="20.0" prefWidth="350.0" promptText="Select a company">
                  <Insets bottom="20.0" left="75.0" top="20.0" />
            <TableView fx:id="listQuote" prefHeight="200.0" prefWidth="200.0" VBox.vgrow="ALWAYS">
                <TableColumn fx:id="symbolCol" prefWidth="75.0" text="Symbol" />
                <TableColumn fx:id="companyCol" prefWidth="241.0" text="Company" />
                <TableColumn fx:id="lastpriceCol" prefWidth="153.0" text="Last Price" />

This XML already contains some links to code we will add later in the class.
Save the .fxml file, right click the file and select ‘Open with Scene Builder’
The Scene Builder will start up and display the following screen :


Important here, is the Hierarchy block at the bottom left of the screen. It shows the structure of the layouts and components on the screen. We will use a BorderPane as the root layout, where a Label is added in the top area to use as a title. In the center area of the border pane, a VBox is added, containing a Combo Box (for selecting the quotes) and a TableView to view the quotes.

The Application

Now that we got the layout in place, we’ll start coding.
First of all, you can remove the generate package ‘application’ with its contents. It was generated by default by Eclipse, but we won’t be using it anymore.
Next step : create a new java class in the eu.iadvise.stockticker package, and call it Use the following code :

public class MainApp extends Application {

	private Stage primaryStage;
    private BorderPane rootLayout;

    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("BATS Ticker Application");
        FXMLLoader loader = null;
        try {
            // Load the root layout from the fxml file
            loader = new FXMLLoader(MainApp.class.getResource("MainUI.fxml"));
            rootLayout = (BorderPane) loader.load();
        } catch (Exception e) {
            // Exception gets thrown if the fxml file could not be loaded
        	System.out.println("FXML NOT LOADED !!!!!");
        Scene scene = new Scene(rootLayout);

	public static void main(String[] args) {

This is our primary class, where, first we set the title of the application window, then, we load the fxml that is used as layout, and then, we launch our application. By now our package explorer should look like this :


When you right click ‘StockTicker’ -> Run As -> Java Application, the application should be launched and will look like this :



The code for the REST call

Before we continue with the JavaFX components, we will create the necessary classes to execute the REST call, that picks up the stock quotes.

First, we create a Company class that will be used to populate the combo box.

public class Company {

	private String symbol;
	private String name;

	public Company(String symbol, String name) {
		this.symbol = symbol; = name;
	public String getSymbol() {
		return symbol;
	public String getName() {
		return name;

	// This method returns the value that is shown in the combobox.
	public String toString() {

	public static List<Company> getListCompanies() {
		List<Company> list = new ArrayList<Company>();
		list.add(new Company("SIRI","SIRIUS XM HLDGS INC COM"));
		list.add(new Company("ABX","BARRICK GOLD CORP COM"));
		list.add(new Company("GE","GENERAL ELECTRIC CO COM"));
		list.add(new Company("TLM","TALISMAN ENERGY INC COM"));
		list.add(new Company("AAPL","APPLE INC COM"));
		list.add(new Company("SPLS","STAPLES INC COM"));
		list.add(new Company("MSFT","MICROSOFT CORP COM"));
		list.add(new Company("PFE","PFIZER INC COM"));
		list.add(new Company("ORCL","ORACLE CORP."));
		list.add(new Company("BAC","BANK AMER CORP COM"));
		list.add(new Company("XOM","EXXON MOBIL CORP COM"));
		list.add(new Company("AA","ALCOA INC COM"));
		list.add(new Company("KO","COCA COLA CO COM"));
		list.add(new Company("C","CITIGROUP INC COM NEW"));
		return list;

The getStockQuote method will execute the REST call to fetch the stock prices. Therefore we added the jersey-bundle-1.18.jar that contains all the necessary JAX-RS class to execute the call. Get this jar from : and add it to the project’s build path.

To get the result from the REST call we create the StockQuote class. This is basically just a value object. :

public class StockQuote {

	private String name; //		Name of the company
	private String symbol; //		The company's ticker symbol
	private double lastPrice;//		The last price of the company's stock

	public String getSymbol() {
		return this.symbol;

	public String getName() {

	public double getLastPrice() {
		return this.lastPrice;

	public void setName(String name) { = name;

	public void setSymbol(String symbol) {
		this.symbol = symbol;

	public void setLastPrice(double lastPrice) {
		this.lastPrice = lastPrice;

	public String toString() {
		return "StockQuote [name=" + name + ", symbol=" + symbol
				+ ", lastPrice=" + lastPrice + "]";


Finally, we need to add the stock quote class that will be used in the observable list. :

public class StockQuoteOL {

	private StringProperty symbol; //	Name of the company
	private StringProperty name; //	Name of the company
	private DoubleProperty lastPrice;//	The last price of the company's stock

	public StockQuoteOL(String symbol, String name, Double lastPrice) {
		this.symbol = new SimpleStringProperty(symbol); = new SimpleStringProperty(name);
		this.lastPrice = new SimpleDoubleProperty(lastPrice);

	public StringProperty getSymbol() {
		return symbol;

	public void setSymbol(StringProperty symbol) {
		this.symbol = symbol;

	public StringProperty getName() {
		return name;

	public void setName(StringProperty name) { = name;

	public DoubleProperty getLastPrice() {
		return lastPrice;

	public void setLastPrice(DoubleProperty lastPrice) {
		this.lastPrice = lastPrice;


The StringProperty and DoubleProperty var’s will cause the components to update if the values of these variables are updated.

The JavaFX code

For each fxml in JavaFX, we create a controller class that contains the code handling all UI actions. So we create a class with the following content :

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Duration;


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;

public class MainController {

    private ComboBox<Company> cbQuote;

    private TableView<StockQuoteOL> listQuote;
    private ObservableList<StockQuoteOL> listQuoteObservable = FXCollections.observableArrayList();
    private TableColumn<StockQuoteOL, String> symbolCol;
    private TableColumn<StockQuoteOL, String> companyCol;
    private TableColumn<StockQuoteOL, Number> lastpriceCol;    

    private ScheduledService<ObservableList<StockQuoteOL>> service;
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
    public void initialize () {
        // fill up combobox with a list of companies
    	ObservableList<Company> listCompaniesObservable = FXCollections.observableArrayList();
        // add a change listener on the combobox
    	cbQuote.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Company>() {
			public void changed(ObservableValue<? extends Company> observable,
					Company oldValue, Company newValue) {
	    			StockQuote stockQuote = getStockQuote(newValue.getSymbol());
	    			listQuoteObservable.add(new StockQuoteOL(stockQuote.getSymbol(),
	    					stockQuote.getLastPrice()) );
        // configure the listView with the stock quotes
    	symbolCol.setCellValueFactory(cellData -> cellData.getValue().getSymbol());
    	companyCol.setCellValueFactory(cellData -> cellData.getValue().getName());
    	lastpriceCol.setCellValueFactory(cellData -> cellData.getValue().getLastPrice());
        // define the service to fetch the stock quotes
    	service = new PollingService(listQuoteObservable);
	    service.setOnFailed(new EventHandler<WorkerStateEvent>() {
	    	public void handle(WorkerStateEvent event) {
	    		System.out.println(" Error in call : "+event.getSource().getException().getMessage());
            // start the service that will run every 3 seconds


    class PollingService extends ScheduledService<ObservableList<StockQuoteOL>> {
    	private ObservableList<StockQuoteOL> listStockQuotes;
    	public PollingService(ObservableList<StockQuoteOL> listStockQuotes) {
    	protected Task<ObservableList<StockQuoteOL>> createTask() {
    		return new PollingTask(listStockQuotes);

    public class PollingTask extends Task<ObservableList<StockQuoteOL>> {
    	private ObservableList<StockQuoteOL> listStocks;
    		public PollingTask(ObservableList<StockQuoteOL> listStocks) {
    			this.listStocks = listStocks;
            @Override public ObservableList<StockQuoteOL> call() throws InterruptedException {
            	for (StockQuoteOL quote : listStocks) {
            	return listStocks;

    public static StockQuote getStockQuote(String symbol) {
        Client c = Client.create();
        WebResource r = c.resource(""+symbol);
        ClientResponse response = r.accept( MediaType.APPLICATION_XML_TYPE).get(ClientResponse.class);
		StockQuote stockQuote =  response.getEntity(new GenericType<StockQuote>() {});
		System.out.println("Result REST call:"+stockQuote);
		return stockQuote;


This controller class contains the code for our MainUI.fxml layout.

To add this controller, open the MainUI.fxml in the scene builder, open the Controller section in the Document section, and select this class from the dropdown. (the eclipse plugin adds all possible controllers to this list)



Remark : after updating and saving the .fxml file using the scene builder, make sure you refresh (F5) the file in Eclipse, otherwise the changes will not be picked up.

The member variables of the controller class, annotated with @FXML, refer to components in the .fxml file, defined with ‘fx:id’. Eg. : open the fxml in scene builder and select the combobox. in the Code section, you see the name of the member in the fx:id : cbQuote.


Now we have our layout and the components, and the bindings between these components and the member variables in the controller class in place. The next step is to add functionality to the components.

In the initialize() method is executed on startup, and contains code for :

  • fill the combobox with a company list
  • add change listener on the combo box and add company
  • configuration of the list view for the stock quotes
  • definition of the service to fetch the stock quotes
  • Connect observable lists to our listview :
    Any changes (adding or updating of objects) in the observable list will now immediatly result in an update in the component.

As JavaFX runs in 1 thread, we will have to execute the REST service call to fetch the stock prices in a seperate thread, otherwise, the main UI would freeze during the call.

JavaFX has a few classes in the javafx.concurrent.* package that can be used to tackle this problem.

We wrote an extension on the ‘ScheduledService’ class : This class executes a Task with any given time between the calls. Our Task ( will fetch new prices for every company that is currently present in the listview. The service as a few methods for configuration purposes :

  • service.maximumFailureCountProperty().set(5) : After 5 failed calls, the service will stop
  • service.setPeriod(Duration.seconds(3)) : The service will be executed every 3 seconds.
  • service.setOnFailed : Callback method if the service fails. (There are more methods available like onSucceed,…)

The service.start() will eventually start the service.

Running the project

Right click the project an select Run as… Java Application.


Remember, if there is no trading at this moment, the prices will not change of course…


New in Java 8 : Consumers and Predicates : a simple introduction

The java.util.function package is new in Java 8 and contains interfaces that are used for lambda expressions and functional references. In this blog, I give a brief introduction of  2 interfaces of this package :

  • Consumer
  • Predicate

For the examples in this blog, we have a list of invoices with name, amount and category :

public class Invoice {
   private String name,amount,category;
   public Invoice(String name,String amount,String category) {
   public String getName() {
   public String getAmount() {
     return this.amount;
   public String getCategory() {
     return this.category;

To generate a list of invoices, we’ll use the following method:

public static List<Invoice> generateInvoices()  {
   List<Invoice> list = new ArrayList<Invoice>();
   list.add(new Invoice("Oracle","1000","SOFTWARE"));
   list.add(new Invoice("Microsof","30000","HARDWARE"));
   list.add(new Invoice("Apple","5000","SOFTWARE"));


A Consumer is an interface that ‘consumes’ an object. It takes an argument and does something with it. It does not return a result.

The Consumer interface has 2 methods :

  • void accept(T t) : contains the code that is executed on t
  • default Consumer<T> andThen(Consumer<? super T> after) : This method returns a consumer that is executed after the previous one and enables you to execute a chain of consumers.

For this demo, we are using the (new in Java8) method of the Collection API :

Collection.forEach(Consumer<? super T> action)

This method executes the consumer ‘action’ on every item of the collection.

First we create 2 methods that each return a Consumer object. The first will print the name of the invoice, the second prints the amount.

Finally we use these 2 methods in a Collection.foreach method.

public static Consumer<Invoice> printName() {
    return new Consumer<Invoice>() {
         public void accept(Invoice invoice) {

public static Consumer<Invoice> printAmount() {
    return new Consumer<Invoice>() {
         public void accept(Invoice invoice) {


As you can see in the last line, first the printName() is executed, and then the printAmount(). This line will print the following :

When an error occurs in the foreach method, an exception is thrown, and further processing of the List stops.


A Predicate is an interface that is used to assign lambda expressions. It has a functional method :

boolean Test(T t )

Predicates are used as stream operations. Stream operations can be executed on Collections in order to execute complex data processing queries. But in this blog we’ll keep it simple, we just want to select all the invoices with category=’HARDWARE’, and put them in a new List.

Using a predicate in combination with the new Streams API, will simplify and shorten our code and make it more readable.

First we define our predicate, and then we’ll use it on our List of invoices. The stream method will filter the List using our predicate, and then collect the items that fulfill the predicate in a new List.

public static Predicate<Invoice> isHardware() {
     return i -> i.getCategory().equals("HARDWARE");

List<Invoice> listHardware = generateInvoices().stream.filter(isHardware()).collect(Collectors.<Invoice>toList());

Our new list will now contain 1 invoice, the one from Microsoft which has ‘HARDWARE’ as category.
As you can see, Predicate is a class that contains a function that we can pass to other classes. Actually it is just a reference to a function, AKA ‘a function reference’.
With Streams, you also sort and map data, before collecting, but that’s for another blog.

So that’s it for now. I hope this blog has shown that, by using Consumers and Predicates, our code will become shorter, cleaner and more readable.


New in Java 8 : Default and static methods in interfaces

Default method’s  (aka Defender methods) in interfaces are new in Java 8. They enable you to define a default implementation of a method in the interface itself.

If an interface is implemented by several classes, it’s hard to add method’s afterwards, as it will break the code and require all implementing classes to define the method as well. Adding a method to the interface, and defining a default implementation for it, will resolve this problem.

Here’s a code example :

public Interface Draw {

public void drawCircle();

   default public void drawRectangle() {

      System.out.println("draw a rectangle");



Implementing classes that have not defined the drawRectangle() method, will print “draw a rectangle” when drawRectangle() is executed on them.

Interfaces that extend this interface can

  • define nothing, in which case the method will be inherited
  • declare the default method again with no implementation, which will make it abstract
  • Redefine the default method so it get’s overridden

These default methods were added to Java in order to be able to implement the new Streams API. As they needed to update the Collection interface, adding the stream() and parallelStream() methods. If they didn’t had the default method, they should have updated all classes that implement the Collection interface.

Static methods

Also new in Java 8 is the use of static method’s in an Interface.

So now, drawRectangle()  could also be defined as a static method, but that would give the impression that it is a utility or helper method, and not part of the essential core interface. So in that case, it’s better to go for the default method.

You could argument that an abstract class would have done the job as well. But as Java has single inheritance, that choice would narrow down our the design possibilities. And as the poster above your bed is shouting every day : ‘Favor composition over inheritance!!’ right ? So we want to avoid inheritance anyway.

So what will happen if you try to implement 2 interfaces with the same default methods ? Well, you will get the following compile time error :

Duplicate default methods named [methodname] with the parameters () and () are inherited from the types [interface1] and [interface2]

To avoid this error, choose an implementation of one of the interfaces :

interface Draw{
   default void circle() {
     System.out.println("draw circle");
interface Print{
   default void circle() {
     System.out.println("print circle");

class MyClass implements Draw, Print {
   public void circle() {;

That’s it, a quick overview of this new feature in Java 8.

Introduction to Websockets and JSON-P API in JEE7

Websockets (JSR 356) and the JSON-Processing API (JSR 353) are both introduced in the JEE7 specification. Together with JavaScript an HTML5, they enable web applications to deliver a richer user experience.

Websockets allow you to communicate bidirectional and full duplex over TCP, between your server and different kind of clients (browser’s, JavaFX… ). It’s basically a push technology, where, for example events or data originating from the server or a client, can be pushed to all the other connected clients.

In our demo , JSON strings are send between client and server, so that’s where the JSON Processing API comes in. It’s a  portable API that allows you to parse, generate, transform and query JSON by using the streaming or model API. But you could also send XML or any other proprietary format.

Serverside components

  1. A java class annotated with
    @ServerEndpoint(value=”/endpoint”, decoders=EncodeDecode.class, encoders=EncodeDecode.class)
    with following method annotations :
    @OnOpen : when connections is open
    @OnMessage : when a message comes in
    @OnClose : when a message is closed
  2. A java class that encode/decodes the message from/to JSON and Java object. (That’s where the JSON-P API comes in).

Clientside component

An html file that contains JavaScript to communicate with our server endpoint. Communication is done through a WebSocket object, declared as follows :

connection = new WebSocket(‘ws://localhost:8080/mywebsocket/endpoint’);

will trigger the @OnOpen method of our server side endpoint.

connection.onmessage : fired when a message comes in

connection.send : will trigger the OnMessage annotated method of our endpoint

connection.close : will trigger the OnClose annotated method of out endpoint


It’s a screen that sends messages to all the connected clients, including itself. When the client opens a connection on the server, his session is added to a list of active sessions. When a client sends a message to the server, it is distributed to all the sessions in the list. When the client closes his browser tab or window, his session is removed from the list. The data that we send, can be any complex JSON or XML model. To keep it simple, we just send a simple string.

This application needs to be deployed on a JEE7 compliant servet. So at this moment (May 2014) it will only run on Glassfish 4.0 or WildFly 8.

The war file can be found here. After deployment, open url (for Glassfish) http://localhost:8080/mywebsocket/socket.html.

 The Code

Java endpoint

package be.iadvise.mywebsocket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value="/endpoint", decoders=EncodeDecode.class, encoders=EncodeDecode.class)
public class MyEndPoint {
 // contains list of active sessions
 private static List<Session> sessions = Collections.synchronizedList(new ArrayList<Session>());

 public void onOpen (Session s) {
 System.out.println("Open session : no of sessions = "+sessions.size());

 public void onMessage (MyMessage msg, Session s) throws IOException, EncodeException {
 for (Session session : sessions) { // loop over active sessions and send the message.
 public void onClose (Session s) {
 sessions.remove(s); // remove session from the active session list.

Java Decode/Encode message

package be.iadvise.mywebsocket;


import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

 * This class will encode/decode the messages from/to the client.
 * Decoder : from client to server -> converts the JSON to MyMessage object
 * Encoder : from server to client -> converts MyMessage object to JSON
 * We are using JSON, but you can use XML or any other format.
public class EncodeDecode implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { 

 public MyMessage decode(String txt) throws DecodeException {
 Reader reader = new StringReader(txt);
 JsonReader jsonReader = Json.createReader(reader);
 JsonObject object = jsonReader.readObject();
 String text = object.getJsonString("text").getString();
 return new MyMessage (text);

 //Check if decode is possible. If not, return false
 public boolean willDecode(String s) {
 System.out.println("Will decode asked for " + s);
 return true;

 public void init(EndpointConfig config) {
 System.out.println("init called on chatdecoder");

 public void destroy() {
 System.out.println("destroy called on chatdecoder");

 public String encode(MyMessage object) {
 System.out.println("I have to encode " + object);
 StringWriter sw = new StringWriter();
 JsonGenerator generator = Json.createGenerator(sw);
 generator.write("text", ((MyMessage)object).getText());
 String answer = sw.toString();
 System.out.println("I encoded an object: " + answer);
 return answer;

Java message

package be.iadvise.mywebsocket;

public class MyMessage {
private String text;
public MyMessage(String text) {
this.text = text;
public String getText() {
return text;
public void setText(String text) {
this.text = text;
public String toString() {
return "MyMessage [text=" + text + "]";

The html file

<script language="javascript">
var connection;
var me;
function openSocket() {
connection = new WebSocket('ws://localhost:8080/mywebsocket/endpoint');
connection.onmessage = function(evt) {
var x = JSON.parse(;
mytext = x.text;
var chld = document.createElement("p");
chld.innerHTML = mytext;
var messages = document.getElementById("messages");

function talk() {
var txt = document.getElementById("msg").value;
var message = {
function closeSocket() {
alert('closing socket')
connection.onclose = function () {}; // disable onclose handler first

<script type="text/javascript">
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener ("beforeunload", closeSocket, false);
else {
if (window.attachEvent) { // IE before version 9
window.attachEvent ("onbeforeunload", closeSocket);
<body onLoad="openSocket();">
<!-- <table id="chatbox" style="display:none"> -->
<table id="chatbox">
<tr><th width="400">messages</th></tr>
<td width="400" id="messages">
<input type="text" id="msg"/>
<input type="submit" value="send" onclick="talk(); return false;"></input>


Websockets are a huge improvement for building rich applications. This is the first time that push technology is actually build in the JEE framework. Before that, we had to use polling or other techniques in order to get the same results. In this blog, I showed that you don’t need much code to start off. Once you get this working, you can gradually go further building more complex sockets.