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…


Java 8 and Spring 4

On March 27, 2014, the Spring community was happy to announce the Spring Framework 4.0.3. The reason why is that it was the first release of the Spring Framework with Java 8 support. Since then, the Spring team worked very hard to provide major updates for the Spring Framework to be even more supportive towards Java 8. As of September 4, 2014, the Spring Framework 4.1 has arrived with even more support towards the Java community.

Lambda support in Spring 4.0

A good example to show the Lambda support in Spring is the JdbcTemplate class. If we would like to obtain female employees and map them as an instance of type Employee, we could do something like this:

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

jdbcTemplate.query("SELECT first_name, last_name FROM employee WHERE gender = ?",
                   ps -> {ps.setString(1, "FEMALE");},
                   (rs) -> new Employee(rs.getString(1), rs.getString(2)));

The complete list of Spring 4.0 features can be found here.

Optional for injection points and MVC handler parameters in Spring 4.1

As of Spring 4.1, JDK 1.8’s java.util.Optional is now supported for @RequestParam, @RequestHeader, and @MatrixVariable controller method arguments. This means that while using Java’s Optional, you make sure that parameters are never null.

The following example shows an example of a @RequestParam in Spring MVC prior to version 4.1.

public String findEmployee(@RequestParam(value = "employeeId") String employeeId) {
  StringBuilder response = new StringBuilder("id: ");
  return response.toString();

When calling the findEmployee method without providing an employeeId, the method will return a NullPointerException. This can be solved by Java’s Optional element.

public String findEmployee(
  @RequestParam(value = "employeeId") Optional<String> employeeId){
  StringBuilder response = new StringBuilder("id: ");
  employeeId.ifPresent(value -> response.append(employeeId.toUpperCase()));
  return response.toString();

The same result can be achieved for the @RequestHeader, and @MatrixVariable annotations.

The complete list of Spring 4.1 features can be found here.

HTTP/2 server push

HTTP/2 general

In general HTTP/2 is about optimizing server resource usage. This is mainly achieved by using 1 connection between server and client and re-using that connection for all requests/responses for the duration of the session.

This is in sharp contrast with HTTP/1. Where a connection is created, a request is sent, a response is received and the connection is terminated. This is overhead is more or less hidden to the user because multiple connections are used in parallel.

HTTP/2 server push

HTML pages reference many other resources. Using HTTP/1 the client needs to parse the HTML page, identify the referenced resources and fetch them. Every round-trip incurring the connection setup/breakdown overhead.

Using HTTP/2 the server can send these referenced resources to the client before they are needed and because the same connection is used there is no connection setup/breakdown overhead.

Use cases

Pushing page resources before they are needed will make a site/application more responsive to it’s users. But doing this manually for all pages of an application is only going to be feasible for the smallest of applications.

Web/ UI component frameworks may push framework resources that are needed. Multiple approaches can be taken in this space. All framework resources can be pushed or only the resources that are needed based on the components of the framework that are used.

What is available

Since HTTP/2 is a draft spec, it is still early days for HTTP/2. Currently there is no standard Servlet API but that can’t stop us, Jetty already has an experimental API.

Google Chrome Canary has support for HTTP/2 when started with –enable-spdy4 as start parameter.

Firefox has support for HTTP/2 when the network.http.spdy.enabled.http2draft is switched on.

Test case

In order to test server push I’ve taken one of my panoramic vacation photos and sliced it up into 400 parts. This may be a little over the top but as with all tests we want to test the limits.

The test has been executed using 2 web-modules:

  • blog-http1-no-push – containing a servlet on URL /nopush that does not perform any pushes.
  • blog-http2-push – containing a servlet on URL /push that executes server pushes for the image slices.

The blog-http1-no-push web module was deployed to a Jetty server containing only the http, annotations and deploy modules running on port 8080.

The blog-http2-push web module was deployed to a Jetty server containing only the http2, annotations and deploy modules running on port 8443.

Both these setups are available as Docker images:

Both web modules contain a single servlet. The servlets take a rows & columns attribute as parameters. This allows us to control the amount of resources that are contained in the generated page. They also control the amount of resources that are pushed by the blog-http2-push web module.

During testing I did notice that the server sometimes becomes unstable when trying to push all 400 image slices. I’ve contacted the jetty users mailing list, perhaps some additional configuration needs to be set when pushing a lot of resources. I’m waiting for their reply.

How do you use HTTP/2 in code

Initially there was a push method on the Dispatcher class, but while writing this blog the Jetty project deprecated that method and made a PushBuilder available via the Request class.

final Request jettyRequest = (Request) getRequest();


Checkout the sources on Github

Performance difference

In order to have a correct test case I’ve deployed the Docker images in the Google cloud in the us-central1-a zone in order to have real network overhead. Measurements have been taken with cache disabled in Google Chrome Canary using the load number.

HTTP/1 – no push
3.01s (average of 6)

HTTP/2 – push
1.51s (average of 6)

Pretty spectacular difference if you ask me.

Do It Yourself

I’ve uploaded the Docker images to the docker hub so you can try it out and experience the difference yourself.
Use the following command lines to run the test web-modules.

HTTP/1 – no push
docker pull teyckmans/blog-http1-no-push
docker run –name blog-http1-no-push-1a -i -t -p 8080:8080 teyckmans/blog-http1-no-push

HTTP/2 – push
docker pull teyckmans/blog-http2-push
docker run –name blog-http2-push-1a -i -t -p 8443:8443 teyckmans/blog-http2-push

5 hidden gems in Java 8

There’s been a lot of attention for the major new features of Java 8: Lambdas, the streaming API and the new Date and Time API. Of course these are the ones that make this a game changing release, but there’s more to Java 8. Inspired by José Paumard´s Devoxx talk 50 new things we can do with Java 8 I’d like to shed some light on 5 smaller features that will make your life as a Java developer easier. I won’t go 50 like José (and actually… neither did he), but these are the ones you definitely need to see.

Join me!

So we probably all had our fair share of recreating the same boilerplate code over and over again: iterating over a list of values in order to concatenate them with a delimiter to a single String. In Java 7 this would probably look something like this:

List<String> values = ...
StringBuilder result = new StringBuilder("[");
boolean first = true;
for(String item : values) {
  if(first) {
    first = false;
  } else {
    result.append(", ");

While this is certainly more concise and more readable than how the code would have looked in the 1.4 era, before generics and enhanced for-loops, but it still is a hideous pile of boilerplate for something very simple. So now for the Java 8 solution:

StringJoiner joiner = new StringJoiner(", ", "[", "]");

This actually showcases not only the new StringJoiner, but two other Java 8 features as well: method references and the forEach() method on the Iterable interface.

While StringJoiner is actually meant for some behind-the-scenes processing for a Collector in the streaming API (, it does eliminate a lot of boilerplate in more traditional code.

Longing for hashCode

When implementing your own hashCode() method for a class that has long fields, in the past you had to calculate the hash yourself or wrap the long value in a Long object and then call its hashCode() method. In order to avoid unnecessary creation of objects, Java 8 allows you to use the static method Long.hashCode(long value) for this.

Line it up!

Java 7 gave us the very convenient Files class with a lot of useful static helper methods for working files, amongst which Files.readAllLines(Path path). This class is also updated to make the best use of the Streaming API. So now we get the even more useful Files.lines(Path path), which does not return a List of all the lines, but a Stream. This is probably a better programming model in almost all cases. When you read all the lines in a file, you will probably want to process them somehow instead of keeping them in memory. Below an example of reading all the lines in a file and printing out only those lines that start with an “A”.

Path file = Paths.get("path", "to", "file.txt");
try (Stream<String> lines = Files.lines(file)) {
    .filter(s -> s.startsWith("A"))
} catch (IOException ioe) {
  // ...

Repeat after me

A new feature that will probably find most of its use in the Java EE world, is @Repeatable. By annotating your annotation type with the meta-annotation @Repeatable, it can be placed at the same element more than once. Under the hood this still wraps the separate annotations in a container annotation, but it reads a lot better.

Since the annotation is not used within Java SE 8 itself, there are only a lot of imaginary examples circulating on the internet. But then again this feature was introduced with Java EE in mind. So below snippet (derived from the Java EE 7 spec) will likely be a valid JAX-B example in Java EE 8:

public class Foo {
  @XmlElement(name="A", type=Integer.class)
  @XmlElement(name="B", type=Float.class)
  public List items;

Which will below the surface be translated to the current notation:

public class Foo {
    @XmlElement(name="A", type=Integer.class),
    @XmlElement(name="B", type=Float.class)
  public List items;

By default

Default methods on interfaces are often presented as a by-product of Lambda’s, but they can make it a lot easier to create a sustainable future-proof API. A default method is a method on an interface of which the (default) implementation is already provided.

Say for instance your public API exposes the following interface:

public interface Foo {
  void addListener(FooListener listener);

Say for instance that you want to add the possibility to add multiple listeners in one go without breaking the implementations of your customers. This can be achieved by adding a default method:

public interface Foo {
  void addListener(FooListener listener);

  default void addListeners(Collection<FooListener> listeners) {

And many more

While I stick to five here, there are many, many more additions to Java 8. You can find the full list here: