Sunday, 8 October 2017

Automatic updates with dnf-automatic

I have installed the package dnf-automatic, to allow for automatic updates to be installed.

dnf -y install dnf-automatic

There's only one configuration file available in /etc/dnf/automatic.conf.

I have set it to:

apply_updates = yes
download_updates = yes
upgrade_type = security

It shows that the timer is active:

[root@ ~]#systemctl status dnf-automatic.timer
● dnf-automatic.timer - dnf-automatic timer
Loaded: loaded (/usr/lib/systemd/system/dnf-automatic.timer; enabled; vendor preset: disabled)
Active: active (waiting) since Tue 2017-09-19 07:27:51 CEST; 2 weeks 4 days ago

Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.
[root@ ~]# systemctl list-timers *dnf-automatic* --all
NEXT                          LEFT         LAST                          PASSED  UNIT                ACTIVATES
Sun 2017-10-08 08:28:05 CEST  5h 8min left Sat 2017-10-07 08:28:05 CEST  18h ago dnf-automatic.timer dnf-automatic.service

1 timers listed.

References - Automatic package updates with dnf
Linux Audit - Automatic Security Updates with DNF

Monday, 2 October 2017

Running Java Programs Online

I have been looking around for an online Java IDE (Integrated Development Environment), so I can do my programming whenever whereever.

Now there are a lot of free websites available where you can just paste a bunch of java code and have it run. Usually it means having all your java code (classes and everything) inside what is basically a TextArea in the browser. An example of these are listed here with my general view of them.

At the bottom are two options that seem to go more towards a full IDE.

Java Online Compiler
Nice with a Java tutorial to work alongside.
Codingground - Compile and Execute Java Online (JDK 1.8.0)
Seems to have a very nice clean layout.
It seems like a very bare-bones version.
Very few features and the advertising gets annoying quick.
Seems good. The ability to run your program as an applet is a nice touch. Looks a little more impressive than the other options here.
The absolute minimum to run a Java program and the advertising is annoying.
A very clean interface. Every programming language known to man available at your fingertips. Ability to upload programs. Used for practice and for competition. Online IDED for Java
Seems okay, but it is great for mob programming. You can invite your friends and you can hack together in the same program. Can handle many programming languages. Very nice interface, autocomplete and code colours. Seems to be used for interviewing potential software designers.
Seems to have only few features. However, you can add Maven external libraries which is nice.


Codiva at is very nice. It is one of the only ones that I could find that had a very low threshold (you can just try it, you can create an account if you like, but you are not required to) and it is one of the few ones where you can actually create different files, instead of putting all your code into a textarea. It also comes with code highlighting and code completion.


Codenvy seems to be an even more professional IDE, where not only do you have a programming environment, but you actually have a Docker image and stuff. It's available at

I shall examine other highend options where a really full fledged IDE is available in your browser in a later blogpost.

Thursday, 21 September 2017

Google OnBoard - Google Cloud

“Almost all the successful microservice stories have started with a monolith that got too big and was broken up.”
- Martin Fowler1

On the 20th of September 2017, I enjoyed a full day at Eindhoven HighTech Campus listening to Google explain everything about their Google Cloud Platform (GCP)2. It's the 63rd or so time this workshop was given. (20.000 people 36 cities)

Of course, I needed to write some of the stuff down, so here's the stuff.

I liked the April fools joke shorts that were interspersed in the lecture.

The problem everyone seems to be facing is that everything needs to be done faster, and better and there needs to be more focus on building business value, instead of having to spent time administrating the hardware.

This can be seen in the fact that the most expensive item in your organisation are your engineers, and they need to be able to work as efficient as possible. Google noticed in the past that time spent doing things that ultimately were of little value can not be regained and is forever lost.

When it comes to the evolution of clouds, you see the following waves happen:

1st wave - colocation
your kit, someone else's building, yours to manage.
2nd wave - virtualized data centers
standard virtual kit, for rent, still yours to manage.
3rd wave - intelligent services automated everything
invest your energy in great apps

Funnily enough, I am noticing this same trend in my home hobbyprojects as well. It can be summarised as follows:

1st wave
I had my own computer, but to install it in a data centre, it needed a rack-mount. My hardware in somebody elses data center.
2nd wave
My computer now is a VPS that I rent.
3rd wave
I started moving small apps over to the Google App Engine.

For a lot of software companies (mine included) we are still only on the second wave. The products of lots of software companies do not require some of the advantages of the cloud and it therefore makes no sense to make the effort.

You can just assemble the google "hexagons" that your application is going to need. It takes a little work to find out what Google has and how it can be best applied to your situation. Because, everybody's situation is different.

Why choose google? If you do use google, you use the netwerk Google created (which is fast), to access other Google users (which use the same network), which are therefore only a hub away.

Googles network is divided in regions and zones. A region might for example be Europe, and a zone might be a data center in a specific region, for example West-1a.

The Google hexagons can be roughly categorized into four main groups, as displayed in the following most important sheet:


StackDriver is a company which was bought up by Google and it specializes in "supporting glue" for different components in an application:
  • Logging
  • Monitoring
  • Debug
  • Error Reporting
  • Trace

Philips Hue

As an example of what it can do, Philips was there to explain how they have been using the cloud along with their new Smart-bulbs in their home-automation project called Hue.

It is a long day to listen, luckily with the free trial version3 of the Google Cloud Platform, it was possible to follow the two gentlemen along in their path through the different components of the platform.

There were some lighter notes as well. For example the spot-the-security-guard in pictures of the Google Data Center. The Machine Learning demos were quite fun too.

I can highly recommend the workshop, for anyone who wishes to have an idea about what Google can do to help your application become great. The sheets alone give a good impression.


[1] Martin Fowler - MonolithFirst
[2] Cloud OnBoard - Learn how to Build What's Next with Google
[3] Google - Free Trial
Google Developer Group Netherlands
Google QwikLabs
Measure your latency to GCP regions
Coursera - Google Cloud Platform
Google Certified

Wednesday, 20 September 2017

Statics in Java - Answer

The output of the program in Statics in Java:
/opt/tools/java/jdk1.8.0_60/bin/java com.mrbear.Test1
Mount Monadnock

So why don't we get a NullPointerException, which most people would expect?

As indicated in the JLS, static methods are directly called on the Class, not on the Object, so the presence or absence of the object is entirely irrelevant.

This is one of the most compelling reasons for always using the Class to call static methods on instead of the Object. It prevents ambiguity for us poor software developers.

P.S. When you think about it, "null" in Java is actually a bit weird, as it can be forcibly cast to any java Object.


[1] The Java Language Specification, Java SE 8 Edition

Thursday, 14 September 2017

Statics in Java

This one comes straight out of the Java Language Specification1, paragraph
class Test1 { 
    static void mountain() 

    static Test1 favorite()
        System.out.print("Mount "); 
        return null

    public static void main(String[] args) 
What is the output of this program?


[1] The Java Language Specification, Java SE 8 Edition

Wednesday, 6 September 2017

Method Overloading in Java - Answer

The output of the program in Method Overloading in Java:
/opt/tools/java/jdk1.8.0_60/bin/java com.mrbear.App
Hello World!
Brian Goetz
So, from the tutorials1:
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
Quoting2 from the JLS3:
When a method is invoked (§15.12), the name of the class, the name of the method, the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).


[1] Oracle The Java™ Tutorials - Defining Methods
[2] StackOverflow - Overloaded method selection based on the parameters real type
[3] The Java Language Specification, Java SE 8 Edition

Thursday, 31 August 2017

Method Overloading in Java

package com.mrbear;

 * Hello world!

public class App 
    public String getHim(String name) 
        return name;

    public String getHim(Object object) 
        return "Object";

    public static void main( String[] args )
        System.out.println( "Hello World!" );
        App app = new App();
        System.out.println( app.getHim("Brian Goetz"));
        System.out.println( app.getHim((Object) "James Gosling"));
        Object object = "Joshua Bloch";
        System.out.println( app.getHim(object));
What does the program above print to its screen?


Oracle The Java™ Tutorials - Defining Methods

Google Takeout

The wife asked how to download all the photos in Google Photos at once, to store on her computer for easy viewing and backups and all that stuff.

It seems there's a Google producttm for that.

Google Takeout1 2 made by an engineering team at Google with a funny name3.


[1] Googel Product Forums!topic/photos/sLseLCfw6Pw
[2] Wikipedia - Google Takeout
[3] Wikipedia - Google Data Liberation Front

Tuesday, 22 August 2017

Opening Up Java EE

DZone mentioned1 that David Delabassee said on The Aquarium2 that Oracle wishes to move JEE technologies including reference implementations and test compatibility kit to an Open Source Foundation.

For more information on how and why, you'll have to check out the original post of David Delabassee.


[1] DZone - Oracle Opening Up Java EE
[2] The Aquarium - Opening Up Java EE
AgileJava by Ivar Grimstad

Wednesday, 16 August 2017

NLJUG JCP Event - Java 9

There was a session on Java 9 on Friday, the 11th of August 2017 in Utrecht1. I went. JUG-members across the world would dive into as much detail as possible in a short timeframe during an online session. It was coordinated between the NLJUG2 (Dutch Java Users Group), CJUG3 (Chicago Java Users Group) and VJUG4 (Virtual Java Users Group). The JPoint5 company provided the facilities to follow the session together with other Java people, which was very kind of them.

The session was split up into different parts:
  1. "The Pragmatic Developer’s Guide to Java 9” by Simon Maple (vJUG)
  2. "Java 9 and the impact on Maven projects” by Robert Scholte (Apache Maven)
  3. "Java 9 and Performance increases" by Jonathan Ross (CJUG)
  4. "Java EE 8 update" by Josh Juneau (CJUG)

It was quite convenient that Jonathan Ross happened to be in the neighbourhood, as he's usually found in the neighbourhood of Chicago. Apparently he is also fluent in Dutch. The coincidences were staggering.

I shall recap in short order all the subjects that passed the agenda.
What the module system in Java brings to the table is the enforcement of boundaries between code. To my mind this is what is necessary to keep us programmers from unheedinly increasing the entropy in the system beyond manageable limits. Classpath will be replaced with Modulepath. We will have to see how that will work out. There is a new file for expressing the different modules and the current module uses them.
The REPL for Java.
The "top" or "ps" command for Java.
It was already introduced in Java 8, but now it has a new stream() function, which isn't eager like map but lazy like streams are supposed to be.
Ahead-Of-Time compilation (AOT)
Causing faster startup times of your java programs, instead of Just-In-Time compilation (JIT). A big requirement for Internet Of Things stuff. (You cannot wait 10 seconds for your doorbell to start up)
Programmer written hints for the compiler
Compact strings
All string objects use UTF-16, which basically fits into two bytes. The vast majority of the strings in applications can be expressed by just one byte using ISO-8859-1/Latin-1. So for most strings, a byte-array makes more sense than a char-array. A special indicator if a string is UTF-8, will be used to decide upon a byte-array or a char-array for storage. The indicator does not increase memory size due to memory alignment.
Indified strings
Concatenating strings using invokeDynamic instead of StringBuilder. This is a major performance boost.
A way of using primitives without having to wrap them in Objects (for example AtomicInteger). It looks a bit ugly, but it's better than using com.sun.Unsafe.
_ as keyword
Probably a first step for JDK 10 and unused parameters in Lambdas
Private methods in interfaces
Try-with-resources small change
You can now use effectively final variables from outside the try block in the try-with-resources statement
Java 5 will no longer be supported by Java 9 compiler
Time to upgrade your ancient programs!
Jonathan Ross knows a lot about performance. I guess he needs it in his job in the Financial Markets.

Robert Scholte talked about Maven being ready for Java 9, even though our applications might not be ready. Java 9 brings some different requirements to the table, because of modules.

One of the big issues that might arise is that those different requirements might make the uptake of Java 9 a great deal slower than was the case for Java 8. Especially if you do not need modules right now.

Josh Juneau talked about JEE 8, the integration Java 8, and the new and upcoming release of the reference implementation Glassfish (with Payara being very close behind).

Other events scheduled.
August 19th, 2017
Virtual Hackday on Java 9 -
Monday, October 23, 2017
Brian Goetz at the CJUG -


[1] NLJUG JCP Event together with CJUG and VirtualJUG
[3] CJUG
[4] VJUG
[5] JPoint
Java EE Guardians
Java Public House (Podcasts)

Thursday, 10 August 2017

Excluding packages in DNF

In the file /etc/dnf/dnf.conf, you can enter which packages need to be excluded.

I like to exclude java packages, until I am ready for them (as they require a reboot of my application server):
Or for instance:
exclude=kernel* java*
When I am ready to install all packages, regardless of excludes, I can use the commandline below.
$ dnf -y update --disableexcludes=all


Fedora 24: Exclude package from update
SysTutorials - Making dnf/yum Not Update Certain Packages

Thursday, 3 August 2017

EclipseLink Logging

In the persistence.xml I have added the following to enable logging for EclipseLink.

Just for my information (so I don't lose the info).


EclipseLink 2.5.x. Understanding EclipseLink - Specify Logging
Eclipse - EclipseLink/Examples/JPA/Logging

Thursday, 27 July 2017

Do interfaces inherit from Object class in java?

I was thinking this question suddenly at work...

Quick, Batman! To the StackOverflow1!!!

The answer comes straight from the JSL2.


[1] StackOverflow - Do interfaces inherit from Object class in java
[2] JLS Java 8 - 9.2. Interface Members

Thursday, 20 July 2017

mount: unknown filesystem type 'exfat'

When attempting to mount a USB drive, I encountered the following error regarding the filesystem exFAT1:
mount: unknown filesystem type 'exfat'
I had to install fuse-exfat as detailed according to [2].
# yum install fuse-exfat
Redirecting to '/usr/bin/dnf install fuse-exfat' (see 'man yum2dnf')

Last metadata expiration check: 0:00:02 ago on Fri May 12 07:06:52 2017.
Dependencies resolved.
Package        Arch       Version             Repository                  Size
fuse-exfat     x86_64     1.2.5-1.fc25        rpmfusion-free-updates      40 k

Transaction Summary
Install  1 Package

Total download size: 40 k
Installed size: 71 k
Is this ok [y/N]: Y
Downloading Packages:
fuse-exfat-1.2.5-1.fc25.x86_64.rpm              335 kB/s |  40 kB     00:00    
Total                                           118 kB/s |  40 kB     00:00     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Installing  : fuse-exfat-1.2.5-1.fc25.x86_64                              1/1
Mounting after that worked flawlessly.
# mount /dev/sdb1 mydrive
FUSE exfat 1.2.5


[1] Wikipedia - exFAT
[2] Mounting EXFAT formatted pendrives in fedora linux

Thursday, 13 July 2017

Enumerations in EclipseLink

I have a field in the database that does not match with an Enumeration.

So I needed to do a little conversion in EclipseLink, and I didn't know how.

Below is the answer on that one.


EclipseLink - @ObjectTypeConverter
EclipseLink - EclipseLink/Examples/JPA/EnumToCode

Thursday, 6 July 2017

Lambdas, New IO, and parsing textfiles in a hurry.

Okay, so I needed to do some parsing of a file containing URLs (which I "wget"-ted) and moving the retrieved files to proper locations.

I decided to write a quick Java program to do this instead of messing around with scripting languages or a Linux bash shell.

It worked very well, and I am rather pleased with the result and Java 8.

It contains the following "new/newer/not-very-old" stuff:
  • a lambda
  • a stream (of Strings)
  • a method reference (used as a lambda)
  • the java.nio.file package (New IO)
One small note: lambdas implement an interface. In this case the forEach requires a lambda that implements the Consumer interface. The Consumer interface does not specify an IOException. Therefore, I am required to catch it here and rethrow it unchecked.


[1] Java SE 8 - Official Javadoc

Thursday, 29 June 2017

UML - What do those Arrows Mean?

In PlantUML:
abstract class Animal
interface Behaviour
interface Prey
Animal <|-- Lion : inheritance
Behaviour <|.. Animal : realization/implementation
Lion *-left- Pride : aggregation
interface Grouping
Grouping <|.. Pride 
Prey o-left- Lion : composition
Water <-down- Lion : uni-directional
Habitat -up- Lion : bi-directional
a dotted line with a closed, unfilled arrow means realization (or implementation). The arrow points to the interface.
Inheritance is indicated by a solid line with a closed, unfilled arrowhead pointing at the super class
a solid line with an unfilled diamond at the class which contains the other class
a solid line with an filled diamond at the class which uses the other class
bi-directional association
A bi-directional association is indicated by a solid line between the two classes. In the example, the Lion lives in his Habitat, but the Habitat benefits in some way from the Lion as well.
uni-directional association
A uni-directional association is indicated by a solid line between the two classes. The class that knows nothing of the other class, has an open arrowhead pointing to it. A Lion uses Water, but not the other way around.


[1] Wikipedia - Class diagram
[2] IBM Developer Works - UML basics The class diagram
What's the difference between Aggregation and Composition?

Thursday, 22 June 2017

MessageBodyWriter not found!

I got the following (unhelpful) message in my server log, when I changed some of my Java classes that are translated to JSON (and vice versa).
Severe: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List

Turns out that I added a specific constructor to one of my Java classes, effectively removing the unspecified Default Constructor that Java always adds.

This default constructor is however essential to the proper working of JSON-Java mapping.

Thursday, 15 June 2017

REST-EJB AccessLocalException causes BadRequest(500) instead of Unauthorized(401)

I am using EJBs as REST Services. It works pretty well. I added security on the EJB, by means of security definitions in the web.xml file and appropriate annotations on the EJB (@DeclareRoles and @RolesAllowed).

Unfortunately, when I try to access the methods in the EJB without being properly authorized, I received a 500 BadRequest. Instead I would really like to have a 401 Unauthorized.

I posted a question on StackOverflow1, but I have found the solution2 in the mean time, which I also posted, and will repost here.

It is possible to add an ExceptionMapper to your Application, which can map between an Exception and an appropriate HTTP Response.


My ApplicationConfig has now been expanded with a


[1] StackOverflow - REST-EJB AccessLocalException causes BadRequest(500) instead of Unauthorized(401)
[2] RESTfu­­l Jav­a­ wit­h ­JAX­-­­RS 2.­0­ (Second Edition) - Exception Handling
StackOverflow -

Thursday, 8 June 2017

Casting JSON Object to TypeScript Class

I have implemented some HTTP service for my Angular App using the explanation at [1]. Now in resource [2] it is mentioned that it is important to provide the JSON Object received from the HTTP Service in the constructor of the data model.

I thought I had found a shortcut. I thought that as long as the JSON object received resembled the structure of the TypeScript class, that I could just cast it to the TypeScript class.

This worked fine, until it didn't, and then I got this huge error in my face.

The problem

The problem started appearing when I defined a method in my TypeScript class. Naturally, this method is not available in the JSON Object, and no manner of Casting is going to make it magically appear there.

You get something like:
ERROR TypeError: item.getItemPriceAsInteger is not a function
    at ItemService.webpackJsonp.71.ItemService.updateItem (
    at ItemSettingsComponent.webpackJsonp.183.ItemSettingsComponent.update (
    at ItemSettingsComponent.webpackJsonp.183.ItemSettingsComponent.saveItem (
    at Object.eval [as handleEvent] (ng:///AppModule/ItemSettingsComponent.ngfactory.js:1663:24)
    at handleEvent (
    at callWithDebugContext (
    at Object.debugHandleEvent [as handleEvent] (
    at dispatchEvent (
    at SafeSubscriber.schedulerFn [as _next] (


There are several solutions available as described in [3, 4, 5].

Chosen solution

I like the one provided in [6]. It uses TypeScript Decorators7. It can be installed as an npm package, according to [8].

To anyone using Java, the solution provided has an uncanny resemblance to JPA annotated Entities or JAXB annotated classes.

I am going to go ahead and try this one out, and see how it works.

I'll provide an update, once I get some results.


[1] Angular Docs - HTTP Client
[2] Writing a Search Result
ng-book 2 - The Complete Book on Angular Nate Murray, Felipe Coury, Ari Lerner, Carlos Taborda
[3] StackOverflow - How do I cast a JSON object to a typescript class
[4] StackOverflow - Angular2 cast a json result to an interface
[5] Angular2 HTTP GET - Cast response into full object
[6] Mark Galae - TypeScript Json Mapper
[7] TypeScript - Decorators
Ninja Tips 2 - Make your JSON typed with TypeScript
[8] npm - json-typescript-mapper

Thursday, 1 June 2017


Wow. On the website for bower1, they mention the following quote:
“ ...psst! While Bower is maintained, we recommend yarn and webpack for new front-end projects!”2 3
Damn, it's hard to keep up with the advancements in Front-end Land!


[1] Bower - A package manager for the web
Yarn - Fast, reliable, and secure dependency management.


I have recently changed my security realm settings, and I thought I'd document them here.

I'm still using the flexibleJDBCRealm1 as I've documented in previous blogs2,3.

In the Glassfish administration console, under Configurations -> server-config -> Security -> Realms -> myRealm, the settings are now as follows.
datasource.jndijdbc/mydbthe data source to my database
password.digestSHA-512I have upgraded from SHA1 to SHA2, which seems more secure
password.encodingHEX:128See note below
sql.groupsselect groupid from mmv_groups where name in (?)using a database view, makes it easier to change table layout without effecting the securityrealm
sql.passwordselect password from mmv_users where name in (?)same as above


The SHA-512 encoding always creates 128 characters as the hash.

However, in the source code of the flexibleJDBCRealm, this hash is converted from a byte[] into a hexadecimal string by means of a call "new BigInteger(1, aData).toString(16);".

This effectively means that if the byte[] starts with one or more "0"s, these are removed in the BigInteger call leaving you with a hash that is less than 128 characters.

This is why I need to use "HEX:128", instead of just "HEX".


The values are easily verifiable in the database.

I can just do a
SELECT SHA2(usertable.password, 512) from usertable where user='mrbear';

It should yield the exact same result as the encryption function of the flexibleJDBCRealm.


[1] FlexibleJDBCRealm
[2] Security Realms in Glassfish
[3] Glassfish Security Realms
[4] Installation instructions

Thursday, 25 May 2017

"this" in JavaScript/TypeScript

I have been struggling with using "this" in JavaScript, ever since I got into that area of programming.

There are lots of warnings on the web, where programmers who are used to a certain behaviour regarding "this" (Like me) can fall into this trap.

I recently found some really good resources that explain it.

There's one1 that explains it a little regarding "this" in JavaScript.

But as I have been writing in TypeScript, I was looking for an explanation that focuses on TypeScript and helps me find the best solution to deal with this. I found that one in [2].

For example

So I've got some code that could use a bit of a look-over.

Here's the troublesome bit.

TypeScript has an excellent Tutorial, which I've used time and again to write my things. One of the pages I've used is the explanation regarding HTTP which you can find at [3].

In it they mention a "handleError" method, which can handle HTTP errors of the PlayerService. Convenient, so I used it. It works.

Next, I wished for the handleError method in the PlayerService that takes care of HTTP connections to notify the ErrorsService. So naturally, I inject the ErrorsService into the PlayerService.

Unfortunately, in the handleError, the ErrorsService is 'undefined'. (See line 30 in the gist below)

It is explained in reference [2] why this is, but I like the following quote:
“The biggest red flag you can keep in mind is the use of a class method without immediately invoking it. Any time you see a class method being referenced without being invoked as part of that same expression, this might be incorrect.”
Now there are several solutions for this described in [2].

The solution below is what I came up with on my own, and I don't really like it, but it works.

Local Fat Arrow

I prefer the solution called the "Local Fat Arrow", which looks like this:
I love it!


[1] Mozilla Developer Network - javascript:this
[2] Github/Microsoft/TypeScript - 'this'in TypeScript'this'-in-TypeScript

Thursday, 18 May 2017


Small followup of From Hibernate to Eclipselink1 post.

I am not entirely satisfied about the AdditionalCriteria4 thingy. I find it a chore to have to set a parameter on the EntityManager all the time to enable/disable it.

Biggest issue for me is that parameters set on the EntityManager are required. If they are omitted, an exception is thrown when querying.

Current solution in my software:
Turn the AdditionalCriteria on or off by means of a parameter that needs to be set on the EntityManager.

Looks like this:
Setting the parameter activePersonFilter can be done on the EntityManager as follows:
@PersistenceContext(properties =
  @PersistenceProperty(name = "activePersonFilter", value = "0"),
  @PersistenceProperty(name = "sundaydateFilter", value = "")
private EntityManager em;
entityManager.setProperty("activePersonFilter", 0);

Other solutions

There are some other solutions.
  1. You can remove the additionalCriteria (set it to "") in a subclass, and use the subclass specifically. See [2].
  2. You can customize any mapping in EclipseLink and add the requirements/conditions that you need. See [3].
  3. I could just decide to create a view on the offending database table. Then create two entities. Sounds very similar to the first option.
  4. I could solve the problem in software. Just have EclipseLink not filter anything. (Which is silly, I don't wish for my ORM to get the 1000 persons in the room from the database, if there are say only three persons active.)
  5. I could remove the collection entirely, and retrieve the required Persons using a NamedQuery. (Which is bogus. I like the ORM to deal with this for me, instead of having to do it myself. It's what the ORM is for.)

Customizing a Mapping

I have recently decided to try to customize the mapping specifically in Entities that have collections containing instances of Person class. That way I have more control. See reference [3] on how this works.

It requires a @Customizer annotation.

For instance, in a Room I only wish to see the active persons.

This requires me to define the PersonsFilterForRoom as follows.
the name of the field that contains the collection
the name of the field in the Entity of the collection
the name of the field in the Room entity that identifies it
It works pretty good.


I also noticed that this way I could have two (Lazy! That's the important bit!) Collections in the same Entity at the same time referring to the same Person. One will contain all Persons and one will contain only the Active Persons.

This is ideal, for instance for Guilds.

Like so:
This way the customizer PersonsFilterForGuild is designed to only work on the activeMembers collection.

I like it!


[1] From Hibernate to EclipseLink
[2] StackOverflow - Disable additional criteria only in some entity relations
[3] Mapping Selection Criteria
[4] JPA Extention in EclipseLink - @AdditionalCriteria
Customizing EclipseLink JPA/ORM Relationship Joins

Friday, 12 May 2017

Eradicating Non-Determinism in Tests

A small blog this time.

At work we sometimes have serious problems with non-deterministic tests.

Martin Fowler mentioned how this can be prevented or dealt with.1

I also noticed that these non-deterministic tests are (almost...) always in the end-to-end tests (or the functional tests, or however you wish to call them).

Martin Fowler also has something to say about those2


[1] MartinFowler - Eradicating Non-Determinism in Tests
[2] MartinFowler - TestPyramid

Thursday, 4 May 2017


I am a card-carrying member of the NLJUG0, which provides Java Magazine (not the Oracle one) six times per year.

One of the issues contained an article about REST-assured1.

I have been using SoapUI5 to test my REST services, and that works fine. It's a nice graphical userinterface for me to fiddle with parameters and urls and HTTP requests and even write tests.

I am aware that it is probably possible to integrate SoapUI into my Build Pipeline, but I was really looking for something different. Something more in the line of programming, which is of course my forte. Something I could use in my unit-tests.

REST-assured was exactly what I needed and let me tell you, it's great!


I will provide an example of how I use it.

As you can see, REST-assured is a very nice DSL (Domain Specific Language) and reads easily.

Some explanation of the above:
I wish to log stuff, if the validation/test fails, so I can find out what is wrong. The output looks like
param(name, value)
for setting parameters at the end of the url, like ?stuff=value
pathParam(tag, value)
replaces {tag} in your url with the values. Convenient!
request methods
in the example above, we are using the PUT HTTP Request.
As it is used for testing, it is possible to verify the values afterwards. In the above this is visible as we expect to receive a 204 (NO_CONTENT).

We can extract the response, as is done above, to verify for example the json payload (if there is one) or get cookie values.

In the above example it is essential for the followup calls that we get the JSESSIONID cookie out of the request.

In subsequent REST calls, it is obvious that we need to send along the same JSESSIONID cookie.

See for more information reference [4].

Some notes

I tried to send parameters, but a POST defaults to FORM parameters in the body, but I already have a BODY. But using "queryParam" instead of "param" fixes this problem.

I do enjoy using the "prettyPrint" method on a Response, to properly format a JSON body and dump it to standard output and see what I get. It's nice.

Getting some values out of your JSON formatted response body does require some serious work, though. Needs more research.

I am not entirely sure, I do not enjoy using http status codes like 200 or 204. I prefer something more readable like "NO_CONTENT", but I suppose I can deal with it myself. No biggy.

Update 14/05/2017: I'm also slightly sorry to find out that rest-assured includes Hamcrest. I prefer AssertJ at the moment myself.


The article in Java Magazine also mentioned WireMock3.

Though I do not use it, it seems excellent for testing the other side of the communications, if you need to test a client that communicates with a server via rest calls.


[1] REST-assured
Teije van Sloten Java Magazine | 01 2017
[2] GitHub - Java DSL for easy testing of REST services
[3] WireMock
[4] GitHub - RestAssured Usage
[5] SoapUI
Testing REST Endpoints Using REST Assured
RFC2616 - HTTP status codes

Thursday, 27 April 2017

Cucumber @After en @Before Hooks

We're using Cucumber at work to write tests, end-to-end-tests that access the user interface of the web application using Selenium.

I recently added an @After hook to a class that contained my StepDefinitions.

However, this @After hook was also called by all other scenarios1, which was not my intention.

As a matter of fact, that @After I added was executing similar code as an @After in another StepDefinition class. I verified that both @After annotated methods were executed for each and every scenario, and they were.

So I decided to move all @After annotated methods into a "GlobalStepDefinition" class, and collaps all of them into one method.

Incidentally, reference [3] shows why we should not have many of these end-to-end tests.


[1] GitHub Issues - Before and After methods invoked for unused step definition classes #1005
[2] Cucumber - Polymorphic Step Definitions
[3] - TestPyramid

Sunday, 23 April 2017

Problems with Resolution and My Monitor in Fedora Core 25

Well, my monitor always has been a bit of a problem child, but it worked, so I didn't mind.

I let it bounce once on the floor, but besides some slight discolouring in the lower-right corner, it was fine.

It reports EDID settings that are completely crap, but I got used to ignoring those, using xrandr.

XRandr settings that work for me

The following settings work:
xrandr --newmode "1920x1440" 339.50  1920 2072 2280 2640  1440 1443 1447 1514 -
xrandr --addmode VGA-0 1920x1440
xrandr --newmode "1600x1200" 235.00  1600 1728 1896 2192  1200 1203 1207 1262 -
xrandr --addmode VGA-0 1600x1200
xrandr --newmode "1280x1024"  159.50  1280 1376 1512 1744  1024 1027 1034 1078
xrandr --addmode VGA-0 1280x1024
xrandr --output VGA-0 --mode 1920x1440


Then I upgraded to Fedora Core 25, and my monitor showed me a handsome 1024x768, which was a disappointment to say the least. (I'm used to 1920x1440.)

Using xrandr gave me the cryptic error message:
bash-4.3$ xrandr --output XWAYLAND0 --mode "1920x1440"
xrandr: Configure crtc 0 failed
After some research I noticed that Fedora Core 25 is the first one to use Wayland1 as the default.


Switching back to the old Xorg2 fixed my problem.

Checking graphics card

bash-4.3$  lspci -nnk |grep -A 3 -i vga
01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Juniper XT [Radeon HD 5770] [1002:68b8]
        Subsystem: ASUSTeK Computer Inc. Device [1043:0344]
        Kernel driver in use: radeon
        Kernel modules: radeon


[1] Wayland Desktop
[2] Fedora Project - Switching back to Xorg - how to install amd/ati driver on fedora 25?
AskFedora - How to add a custom resolution to Weyland Fedora 25?
ArchLinux - Forcing modes and EDID
Bugzilla Redhat - My Bugreport

Saturday, 15 April 2017

Keyset pagination

In the past I have used the MySQL equivalent of pagination. In other words, the splitting up of a ResultSet into pages of a fixed number of entries, by means of using SQL1.

It looks like the following:
SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15
For compatibility with PostgreSQL, MySQL also supports the LIMIT row_count OFFSET offset syntax, which I've used in the past.


Performance is a key point here, as MySQL requires the retrieval of the results in order to determine where the offset starts.

If the table is large, retrieval of pages at the end of the table are going to be extremely slow.


A better way to deal with this, is to not use an offset, but use the key of the last row of the previous page, and use that in the query for the next page.

Obviously this only works if the resultset is sorted.

For more references that explain this a lot better, see [2] and [3].


[1] MySQL 5.7 - 14.2.9. SELECT Syntax
[2] Use the Index, Luke! - We need tool support for keyset pagination
[3] Use the Index, Luke! - Paging Through Results

Thursday, 6 April 2017

Try Git

To anyone who is absolutely new to the exciting new world of Git1.

There seems to be a little website where you can try Git2, working in a (very very) limited sandbox environment.

What is Git?

If you wish to know what Git is, there are loads of interesting articles on teh interwebs that explain it very well.

But I did find the following explanation in the README provided with the source tar-ball:
The name "git" was given by Linus Torvalds when he wrote the very
first version. He described the tool as "the stupid content tracker"
and the name as (depending on your mood):

 - random three-letter combination that is pronounceable, and not
   actually used by any common UNIX command.  The fact that it is a
   mispronunciation of "get" may or may not be relevant.
 - stupid. contemptible and despicable. simple. Take your pick from the
   dictionary of slang.
 - "global information tracker": you're in a good mood, and it actually
   works for you. Angels sing, and a light suddenly fills the room.
 - "goddamn idiotic truckload of sh*t": when it breaks


[1] Git --distributed-is-the-new-centralized
[2] Try Git

Thursday, 30 March 2017

Setting session timeout in Glassfish

People complained that their sessions timed-out too quickly in Glassfish.

I checked and it is set to 30 minutes (default 1800 seconds), just a tad too little.

Increased it to 2 hours (7200 seconds).

Just went to Configurations - Web Container - Session Properties - Session Timeout.

It changes the domain.xml:
<session-properties timeout-in-seconds="7200"></session-properties>


Of course, this completely and utterly failed to work in my case.

It turns out I already had a session timeout specified in the web.xml.
The session timeout in the web.xml is specified in minutes.

You can also specify it in the glassfish-web.xml file.1
        <property name="timeoutSeconds" value="600"/>
        <property name="enableCookies" value="false"/>


You do need to check which setting takes precedence in your application. It's not clear from the documentation.


[1] Glassfish 4.0 Application Deployment Guide
iT Geek Help - Glassfish web container tuning settings
StackOverflow - How to set session timeout in glassfish-web.xml configuration file?

Thursday, 23 March 2017

AssertJ vs. Hamcrest

I recently came across a piece of code that used a Stack1. The Stack seems to inherit from Vector. The JavaDoc indicated (and so did my IDE, I think) that I should be using the Deque2 interface instead. To be precise:
“A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.”
Dequeue basically seems to be a specialized Queue3, that supports element insertion and removal at both ends4.

In order to get to grips with Deque, I decided to write some simple tests. These are JUnit Tests (version 4.12) and in one I used Hamcrest5 and in the other I went for AssertJ6.

Let's see what happens.

A simple compare

assertThat(actual, equalTo(testdata2));


assertThat(transmittedTestdata, hasSize(2));

Null Values

assertThat(actual, not(nullValue()));


@Test(expected = NoSuchElementException.class)
public void testEmptyDequeueException()
  Deque<Testdata> transmittedTestdata = new ConcurrentLinkedDeque<>();
  Testdata pop = transmittedTestdata.pop();


A comparison between the required imports of Hamcrest and Assertj is interesting:
import java.util.Deque;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentLinkedDeque;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Deque;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentLinkedDeque;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;


  • I really like the AssertJ fluent API. It feels more natural to me than the Hamcrest one.
  • It is way easier to find the appropriate matchers in AssertJ. I get the full benefit of my IDE code completion.
  • Adding the appropriate import is way easier. Using Hamcrest, I always get a choice of five different imports for the same matcher.
  • I need fewer imports anyways.
So far, I like AssertJ a lot.

I need to work with AssertJ a lot more, to see some of the interesting stuff.


[1] Java 7 JavaDoc - Stack
[2] Java 7 JavaDoc - Deque
[3] Java 7 JavaDoc - Queue
[4] Wikipedia - Double-ended queue
[5] Hamcrest - Matchers that can be combined to create flexible expressions of intent
[6] AssertJ - Quick start

Thursday, 16 March 2017


Our architect recently put together a presentation regarding our new framework using reveal.js1.

I had never heard of reveal.js and I was intrigued. It seems to be a presentation framework that runs in your webbrowser, using npm2 and grunt3 and javascript and MarkDown4 and all that.

I figured I'd give it a try for my next presentation.

I downloaded a release6 and used the very clear instructions on how it works on GitHub5.

Installing a new release, seems to be nothing more than:
- download
- unzip
- edit index.html
- browse to index.html

Luckily, I had the changes our architect made to bring it into line with the company layout guidelines. It was nothing more than a different css file that is based on the "white"-theme (which is also a css file). The default theme when you get a release is the "black"-theme, similar to the one visible at [1].

You can decide to just browse to the file index.html locally to display the presentation, but if you do a "grunt serve" a small webserver is started that serves the webpage and related resources. The latter option provides more functionality.


<div class="reveal">
  <div class="slides">
    <section data-markdown=""

As you can see above, you can specify how the sheets are divided. What exactly the sequence is for detecting a division.

Initializing the presentation is done using:
// More info
      width : 1280,
      height : 1024,
      slideNumber: 'c/t',
      showNotes: true,
      history: true,
// More info
      dependencies: [
          { src: 'plugin/markdown/marked.js' },
          { src: 'plugin/markdown/markdown.js' },
          { src: 'plugin/notes/notes.js', async: true },
          { src: 'plugin/zoom-js/zoom.js', async: true } }
I set the "snowNotes" to true, because I wished to print out the sheets including the notes. See Printing below.


It is easy to add custom CSS to individual slides. For example:
<!-- .slide: data-background="#ffffff" data-background-image="images/background_subtitle.png"  data-background-size="auto 100%"  data-background-repeat="no-repeat" -->
A common one used to change the font of the previous element (useful for source code):
<!-- .element: class="small" -->


Printing your sheets seems to be as simple as surfing to the url:
It generated in Chrome browser a PDF file that you can simply print to file in the browser.


It is very nice, if you are a programmer or web guy and you do not wish to fire up Microsoft Powerpoint.

An advantage is of course that MarkDown files can easily be added to your version control system.

Another advantage is that you can refer to images on the Internet/Intranet. I managed to do just that, by referring to images already on our Intranet Confluence pages. At least the images will always be up to date.

(p.s. It also means that in order to view my presentation properly, one has to be logged into Confluence. I found that out rather quickly, when trying my presentation out in one of our conference rooms.)

I don't really like the markdown setting displayed above, as it is too easy to add one line or remove one line to many.

I also had a problem where I must have made a grammatical mistake, and in my FireFox browser the presentation managed to hang and after several seconds I'd get a "Script is running too long. Do something about it?" message.

There are several keyboard shortcuts for navigation through the sheets during the presentation, which is nice, as the mouse isn't all that handy.

I don't much like the "sheet notes", which are displayed in a separate browser window. I usually have them turned off.


[1] Reveal.ks - the HTML Presentation Framework
[2] NPM
[3] Grunt
[4] Wikipedia - MarkDown
[5] GitHub - reveal.js
[6] reveal.js releases
GitHub- Basic Writing and Formatting Syntax

Thursday, 9 March 2017

Git Stash

This little blog post is just for me to remember my favorite "git stash" commands. It took me a little while to actually use the stash, but that is because IntelliJ provides a similar functionality called "shelving", which I had used all this time.

I use branches a lot when using Git, and the problem there is that Git usually complains if I wish to change branches, while I still have uncommitted changes in my current branch. Therefore the "stash" command is for me very valuable.

Stash your current uncommitted changes:
$ git stash

Get your uncommitted changes back from the stash:
$ git stash apply

Get a list of your current stashes:
$ git stash list
stash@{0}: WIP on master: 049d078 added the index file
stash@{1}: WIP on master: c264051 Revert "added file_size"
stash@{2}: WIP on master: 21d80a5 added number to log
Remove a no longer needed stash:
$ git stash drop stash@{0}
Dropped stash@{0} (364e91f3f268f0900bc3ee613f9f733e82aaed43)
One command I particularly like is this one that does both an apply of your stash and once done automatically removes it from the list of stashes:
git stash pop

The stash has a lot of similarities to your standard Stack implementation (or Dequeue, depending on your point of view.)

I notice that if I do not clean up the place or use the "pop" subcommand, that my list of stashes tends to grow quite long unobtrusively.


6.3 Git Tools - Stashing
Atlassian Tutorials - Git Stash
Ariejan De Vroom - GIT: Using the stash
Git Stash - Man Page

Thursday, 2 March 2017

Maven and the Dangers of Snapshots

Recently we've been causing problems in the regular builds of branches of our software.

Basically the problem is our own fault and is related to Maven Snapshots.

According to the guide1, a Snapshot is a library that is still under development, and may change rapidly as new versions of the Snapshot are pushed to the Nexus regularly.

If a dependency on a Snapshot is defined in your pom.xml, then Maven, as it should, always picks the latest Snapshot.

This is fine and dandy if you are currently developing your software, and you want the newest of the new of the libraries that your other software teams are developing.

The Problem

It means that once you create a stable release of your software (and the appropriate Git branch for it to live in as well, of course) it is important to replace the Snapshot in the pom.xml with the appropriate released version.

We neglected to do just that.

The Consequence

Our branch containing the release version of our software suddenly bombed with compile errors in the Deployment Pipeline.

This caused the maintenance people a headache, as the Git revision of the branch had not changed, between the previous build (which compiled just fine) and the new build (which bombed).

Despite the build being pulled from Git with the exact same revision, it was technically different from the previous build.

All because we kept developing the Snapshot and pushing it into the Nexus.

What we should have done

  • create a proper release of the library
  • change the pom.xml in the branch to refer to this release.
  • create a new snapshot of the library
  • use the new snapshot in the pom.xml of the master branch (which is used for development)
Now the build of both the branch as well as the master should compile again.


[1] Apache Maven - Getting Started
Continuous Releasing of Maven Artifacts
Update: reference added.

Thursday, 23 February 2017

A Natural Progression Towards Lambda

At my work, in order to deal with a grid1 in the frontend and a list at the backend, we use a DataModel at the backend.

It seems simple enough, and used to work as follows:
private List<Person> list = Arrays.asList(new Person("Jim"), new Person("Jack"));

private ListDataModel<Person> dataModel = new ListDataModel<>(list);
This had some shortcomings when for example the user decided to select a different department, executing this code:
list = findPersonsByDepartment(department);
This seems to work just fine. A person selects a different department, and the employees data model updates itself. Or so one would think.
What happens is that the ListDataModel retains the old list. So, the frontend is never updated.

Reusing the same list

Because of this little problem, our code retains a lot of the following statements, to make sure the same list is used over and over again:
It seems a slightly convoluted way to doing things.

Anonymous inner classes

We soon found out that anonymous inner classes would solve this problem better, and in fact there are more anonymous inner classes than there are named DataModels in our current code base.

It looks like the following:
private ListDataModel<Person> dataModel = new ListDataModel<Person>() 
   public List<Person> getList() 
     return findPersonsByDepartment(department);
There now, any time the contents of the ListDataModel is requested in the frontend, a new and accurate List containing the department employees is returned.

Passing code

Instead of creating an entire new anonymous inner subclass of a ListDataModel, it might be more elegant to create an interface especially for this purpose, call it the ListProvider interface.

As follows:
public interface ListProvider<T> 
  List<T> getList();

private ListDataModel<Person> dataModel = new ListDataModel<Person>(new ListProvider<>() 
   public List<Person> getList() 
     return findPersonsByDepartment(department);

Using lambdas

The good part is that now with Java 8 we can start using Lambdas.

And in this case, we have an interface containing just one method. This is in essence the definition of a lambda.

So now the proper way to write this would be the following:
public interface ListProvider<T> 
  List<T> getList();

private ListDataModel<Person> dataModel = 
    new ListDataModel<Person>(() -> findPersonsByDepartment(department));
Convenient, isn't it?
In this case, the lambda is called a Supplier2 .


[1] Welcome to the SlickGrid! (outdated sadly)
[2] Supplier (Java Platform SE 8)

Thursday, 16 February 2017

Angular - Semantic Versioning

Angular1 has switched to Semantic Versioning2

So, the brand new thing that is totally hot right now is Angular 4.0.

The versions released, and to be released are available here3.

Contrary to the image in the blog, the word for referring to all this is "Angular".

Looks like version 5 of Angular will be released later in the year.

I hope I can keep up.


[1] Ok... let me explain: it's going to be Angular 4.0, or just Angular
[2] Semantic Versioning 2.0.0
[3] Versioning and Releasing Angular