Thursday, 11 February 2016

My First Lambda

I just implemented my first lambda1. My java code is now officially only Java 8 and up compliant.

My pom was changed as follows:
<project.source.version>1.8</project.source.version>
<project.target.version>1.8</project.target.version>

Original code

The original code looked like this:
Pretty straight forward stuff.

Adding a Lambda

Then we received two change requests, that could be resolved by re-using the method above.

But this time, not everyone was required to see the message. In other words, the list of active players needed to be filtered.

Enter the Predicate2.

Let us say the filtering needs to be done, by those who wish to be kept in the loop regarding roleplaying events. These users contain an Ooc (Out-of-Character) flag.

Calling this can be done using a Lambda, like so:
sendWall("[OOC: " + aUser.getName() + "] " + message + "\r\n", p -> p.getOoc());

Streams

To make things a little more complicated, you can make use of the new Streams3 4 provided in Java 8.

In the example below, I take a stream from the List collection provided by getActivePlayers, filter it by the predicate, and run the writeMessage on each found user. That last one is called a "terminator" as it terminates the stream, i.e. it "does something".

A lot less code than the previous for loop. It seems more complicated, but I guess it just requires me to get used to it.

It also causes me to create another Lambda, as the terminator.

The Old Way

In the old way, calling this method sendWall was done using an inner class, and it looked as follows:

References

[1] JavaTM Tutorials - Lambda Expressions
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
[2] JavaDoc - Interface Predicate<T>
https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
[3] JavaTM Tutorials - The Collection Interface
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
[4] Processing Data with Java SE 8 Streams, Part 1
http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html


Thursday, 4 February 2016

Validation of Beans

Just a small utility function that prints out readable messages on what is wrong with a certain bean (like for example a JPA Entity).

Got a little miffed with the fact that my javax.validation.ConstraintViolationException that is thrown, never shows the exact problem. I always have to drill down into the Exception to find the message in order to fix the problem.

I hope it helps someone.

See for more information about bean validation JSR 303.

References

The Java EE 6 Tutorial - Using Bean Validation
http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html
The Java EE 6 Tutorial - Validating Persistent Fields and Properties
https://docs.oracle.com/cd/E19798-01/821-1841/gkahq/index.html