Skip to content

Category Archives: Java

Change of perspective: A NetBeans testimonial


This post is long overdue since JavaOne 2014. I’m not getting payed for it, it’s more a thank-you to the whole NetBeans team for bringing some fun back into my everyday coding life.

I’ve been an Eclipse user for a long time, i think way back 10 years ago when it didn’t have a name but only version numbers. Back in 2005 it was for us the only real viable Java IDE around. I remember NetBeans as pretty much unusable for us back then and IntelliJ too expensive. Eclipse felt native, fast and actually, intelligent supporting our development.

What we never did was platform development on either Eclipse or NetBeans.

Back then we often had the problem, that some projects were only deployable from the IDE. Or worse: From one developers IDE. Came ANT, things changed for the better, came Maven (downloaded half of the internet) things got even better. Today i wouldn’t touch a thing that is not build able with standard command line tools. I’m actually a big Maven fan, but Maven and Eclipse relationship has been complicated, at least to say, but I made it into a requirement that every productive project or module should be buildable by maven. Having that, we ran into a lot of problems with M2Eclipse over the years, it never was fun. Also updating any installation of Eclipse is a sad thing. Sometimes it works, more often not.

Anyway, we did great stuff with it and with Spring Tools Suite appearing somewhere in 2011/12 for me many problems with Eclipse vanished with the nice pre bundled stuff.

By the end of 2013 i was (and actually, i still am) pretty bad frustrated by project that involves a framework I prefer never ever touching again and some AspectJs that repeatedly crashed *only* in the IDE.

Looking for something relaxing, inspiring i aimed for a clean and simple Java 8 project and i ended up with this. By February / March 2014 the only IDE offering good Java 8 support was NetBeans 7.4 and in March, NetBeans 8, so choosing a new IDE was pretty easy.

Not wanting to change everything, that was one of the first steps:


Setting the profile to “Eclipse” allowed me to keep my old habits regarding shortcuts, navigation and stuff. By now, I’ve switched to the NetBeans profile.

Working out of the box is the great Maven support. Without adding anything to a project (apart from a project specific settings file), everything works as is. Didn’t have any problems regarding lifecycle management or a plethora of additional xml files per dependency like IntelliJ creates. Great.

Learning: NetBeans did help me (and now my coworkers) to get my head around Java 8 lambda expression and basic use case cases:


into this


Pretty basic, sure, but everybody needs a starting point and replacing anonymous inner classes is an immediate win.

Some day i was rewriting a complex computation and i discovered “Use functional expression” hint. I didn’t expect it to work as the variables used weren’t effectively final but NetBeans pretty much did something like this:


The Reduction was actually way more complex than this. I was pretty sure that this was working because I had written tests and already added the JaCoCo Maven plugin which is detected by NetBeans and ensures me that everything is green as described here.

Speaking of code quality: I actually like the NetBeans code formatter, adding curly braces for every branch of control flow and so on. I guess one of the only things i’ve changed are spaces to tabs (yes, i use tabs. I want semantically correct empty space, not spaces).

JavaDukeTeach_larger (Image from Coding Dude) More teaching and learning: NetBeans has an excellent build-in HTML, JS and CSS editor and all of them work hand in hand. The HTML editor proposes CSS classes the platform finds in css files in the projects, as does the JavaScript editor. The later knows about AngularJS functions, attributes and more. Some of my coworkers always look for WYSIWYG editors: I didn’t even bother, i’m way faster with that kind off assist and i learn stuff with it. Also, the pom editor: It completes group and artifact ids and also suggest the most current version. If i do need a GUI editor (for example creating FXML files), NetBeans knows how to call JavaFX scene builder.

The power of content assist also shines with the nb-springboot-configuration-support, which is demonstrated by Geertjan at Oracle.

Other things i’ve used repeatedly: The very fast local history, the ability to restore unversioned files from local history and fast file compares. Fast navigation between classes and corresponding test classes and certainly the good Git integration.

I’ve encountered only some minor problems so far: Sometimes my installation hangs during download of JavaDoc for whatever reason i don’t know. There seems to be a problem with Java 8 parameter names sometimes, but for the last year no bigger deal.

We at ENERKO have used NetBeans 8 through 8.0.2 for the last year creating two successful Spring Boot projects in the energy / commodities market. One an AngularJS application and the other one a traditional, server side rendered Java project. There’s wast knowledge around another Oracle product in our company, namely Oracle Database, but not that much modern Java web stuff, so being able to teach without distraction by tools was essential.

NetBeans IDE helped me a lot learning and teaching modern Java technologies without wasting time on configuring, explaining build failures due to configuration errors etc. and instead concentrating on stuff that actually matters to us: Creating great software. Reducing unnecessary complexity in tooling is an invaluable asset for modern software development.

So, the change of perspective brought by changing our main IDE changed actually more than an IDE.

(By the way, another great application based on the NetBeans platform is the Oracle SQL Developer, useful not only for Oracle databases but for many other databases with JDBC connectors.)

First talk at EuregJUG Maas-Rhine: “Building Modular Java Applications in the Cloud Age”


May i bring the first talk at the newly founded EuregJUG Maas-Rhine to your attention: “Building Modular Java Applications in the Cloud Age” will be held by @bertertman on Thursday, May 28th, 2015 at BitStars HQ, Hanbrucher Str. 40 in Aachen:


Would be great to meet some of you, i really hope we get this JUG going. Thanks a lot to Stefan Pfeiffer aka @dl1ely for all his engagement, i’m happy to be part of it.

What’s the fuss with Java 8 Optional?


I’ve been asked several times lately by colleagues what the Optional<T> is good for, so today some more basic stuff.

You can use the Optional class is as an elaborate null check like

  Optional<String> optionalString = Optional.ofNullable(someString);
  if(optionalString.isPresent()) {
    String string = optionalString.get();
  // Or worse
  // String string = optionalString.orElse(null);
  // null check here

but most of the time, a computed value based on a possible null input value is much more interesting. Here comes map and flatMap.

If the optional value is present, map is used to compute a new value (which is turned into an optional), flatMap has the same purpose but is meant for computations that already return an Optional, otherwise you would end up with an Optional<Optional<T>>:

// Compute the length of a string which could be null
int length = Optional.ofNullable(someString).map(String::length).orElse(0); // Which value is used as default is surely debatable

Here’s a real world example from biking. Spring framework supports Optional request parameters and path variables since 4.1, so i can write a controller method that takes two optional range variables (start and end) like this:

I can use these two parameters to filter a map containing LocalDates as keys without null checks like so:

    // Stream the bikes 
    // and flatMap (concat) their periods into a new stream
    .flatMap(bike -> bike.getPeriods().entrySet().stream())
    // we're only interested in periods before 1.1 of the current year
    .filter(entry -> entry.getKey().isBefore(january1st))
    .filter(entry -> {
	final int year = entry.getKey().getYear();	    		
        // No need for null checks, the optional parameters are mapped to booleans
        // if the values are present, check if the current year is after start respectivly before end
        // otherwise the interval is open and i can map them to true
	return -> v <= year).orElse(true) && -> year < v).orElse(true);
        // Using possible null values the the filter would look like
        // (yearStart == null || (yearStart <= year)) && (yearEnd == null || (year > yearEnd))

Now, it’s actually debatable which expression brings the intention more clearly, but i like the fact that i just can use the parameters as is.

Another interesting Optional method is filter. It takes a predicate and turns a non-empty optional into an empty optional if the predicate doesn’t match. I use it for example for an “default if blank string method”:

 * Returns {@code defaultValue} when {@code value} is empty or blank.
 * @param value A string
 * @param defaultValue A default value when the input string is empty.
 * @return value or defaultValue
public static String defaultIfBlank(final String value, final String defaultValue) {
    return Optional.ofNullable(value).filter(Strings::isNotEmpty).orElse(defaultValue);
 * @param value Value to be checked if empty
 * @return True if trimmed value is not empty
public static boolean isNotEmpty(final String value) {
    return !value.trim().isEmpty();

Do you have interesting use cases for Java 8s Optional?

JavaLand 2015 result: JavaFX 3d mosaic for


JavaLand 2015 resulted in a sweet little toy project for me (See my little reviews of the conference itself here: 24.3, 25.3 and 26.3, JavaLand 2015 was one of the best conferences i attend. Lots of fun, lots of good talking, i really enjoyed it).
Wolf Nkole Helzle had this My-Matrix project going on there and i thought, well, this year i’m doing Daily Fratze for ten years and i alone will have 3650 pictures of myself uploaded to the internet by August and in sum there are over 50.000 images right now, that should be a pretty good idea, creating an interactive mosaic as well (Adastra has already created a beautiful mosaic on her 8th anniverary).

As i don’t want to share the images anywhere else but only in my own daily picture project i had the opportunity to learn some more stuff which you can find here.

The basic idea for this mosaic generator is: Create an accurate color matching algorithm as readible as possible. Lukas Eder had this nice article on dzone why It’s Okay to Stick With SQL and i wanted to see how far can i get with SQL for my goal.

This project includes:

  • Flyway for creating and migrating databases (i didn’t want to run sql-scripts myself)
  • Flyway and jOOQ maven integration for effortless generating dao code at compile time
  • jOOQ in common for all database access
  • An CIE94 color distance algorithm
  • JavaFX 3d for creating a spherical image wall. Kudos and thanks to José Pereda for inviting me and giving me a real great introduction not only to his cool JavaFX presentation tool (which gives live coding a whole new dimension), but also to JavaFX 3D. Next time i try to be not that shy, but was too impressed by this massive Java knowledge all around me.

Also personal thanks to mentioned Lukas Eder, maybe you didn’t notice but you encouraged me a lot in what I am doing at the moment.

You’ll finde the complete source code for this project at github:

dfx-mosaic @ github.

So, how far did i come? Far! First have a look at the JavaFX application, selecting the tiles and rendering them on an image wall and me exploring the scene:

Mosaic generation is done in two steps: Create a database of images including their average color (Average color defined by the arithmetical average of all rgb values in an image). You gotta love Java 8s stream for how simple such things have become:

And then (for example):

Those list of images records: Just put them in a SQL database. I choose H2 for simplicity and i’ve gotta say, Flyway and jOOQ are really a dream time. I used this tutorial and had my Records and DAOs in no time.

I like jOOQs batch api, way easier then to this by hand:


Writing the CIE94 color distance was the hard part, making it usable inside an H2 database is really easy:

create.execute("create alias if not exists f_CIE94_color_distance deterministic for \"de.dailyfratze.mosaic.images.CIE94ColorDistance.compute\"");

I’d prefer having this done also in migration, but the referenced method must be defined at runtime, so no chance here.

The basic idea for my mosaic algorithm is selecting the source image with the least color distance which has not been used in box of 10 by 10 tiles. I could have come up with a more performant algorithm but that would have been as easy as just iterating the tiles of the target image and just selecting it (the variable tiles contains all selected tiles so far):

SQL checked by the compiler, correct in statement, calling stored procedures. All there, readable and really easy to use.

The JavaFX 3d application is nearly identical to the VideoWall on Stack Overflow but serves me well for further experiments.

I plan to arrange the images by year on the z-axis (done, see below), create some dialogs for choosing creating and choosing libraries, settings for tile size and such. If i should have to much time on my hand, i’d love to see touch support, a Raspberry Pie and a touch screen for doing some kind of installment on my 10th anniversary of daily self portraits.

I’ve also included a little terminal application which just writes mosaics to file, the result looking like so:


Compare to the original (taken at Mavericks beach on my trip to JavaOne 2014):


And a screenshot from the JavaFX app with the images spread by year on the z-axis:


Spring: Provide Interoperability between JMS and Springs simple WebSocket messaging


Nearly 2 years ago, excellent WebSocket Support appeared in Spring 4, easily usable using STOMP over Websockets / SockJS on the client side, backed by a pluggable broker on the server side, which can either be simple broker using scheduled executor services to handle message or a full fledged RabbitMQ or ActiveMQ solution.



enables the first solution without much fuss, integrating an existing and running ActiveMQ STOMP transport is nearly as easy:

public void configureMessageBroker(MessageBrokerRegistry registry) {

I’ve already used (and i am using) such a solution in this application, as described here. What you’re doing is not instantiating your own scheduler and transport, but relaying everything to the existing transport which is nice when you don’t want to was resources.

What’s missing here, is some deeper integration.

Using Springs JmsTemplate it’s really easy to send JMS messages and it’s also easy to connect simple beans or services through messages:

Imagine an arbitrary service, not knowing anything about jms:

class SomeCmd {
public class SomeService {
  public void someVoidMethod(final SomeCmd someCmd) {
    System.out.println("Something incredible");

Connecting this to a queue is as easy as:

import javax.jms.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
class Config {
  public SimpleMessageListenerContainer someServiceContainer(final SomeService someService, final ConnectionFactory connectionFactory) {
    // Create an adapter for some service
    final MessageListenerAdapter messageListener = new MessageListenerAdapter(someService);
    // Connect the method 
    // to a queue	
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    return container;

Sending messages is a onliner:

jmsTemplate.convertAndSend("some.queue", new SomeCmd());

If that method isn’t a void method, the result can automatically be passed to another queue:

class SomeCmd {
class SomeResult {    
public class SomeService {
  public SomeResult someNonVoidMethod(final SomeCmd someCmd) {
    return new SomeResult();
// Change in the config
// And added to the config:

What if i want to have the result right available on a web site using WebSockets and STOMP? Although the name sounds similar, the SimpMessagingTemplate has nothing todo with the JmsTemplate, at least not immediately.

As it turns out, it’s relatively simple redirecting the output of bean to the STOMP queue, knowing

Note that the prefix in stomp /queue/ or /topic/ is removed from the string before passing it to ActiveMQ as a JMS destination. Also note that the default separator in MOM systems is . (DOT). So FOO.BAR is the normal syntax of a MOM queue – the Stomp equivalent would be /queue/FOO.BAR

Working with Destinations with Stomp

In the above example

// becomes

Which means: Everything SomeService#someNonVoidMethod returns is send to a STOMP topic call /topic/some/response/topic.

Nice. But it turns out, SimpMessagingTemplate converts the messages body to a nice, readable JSON format, internally proceeded by Jacksons Object Mapper. Without a custom converter, we’ll end up with a MapMessage. To make the outcome of the topic the same, regardless wether produced using SimpMessagingTemplate or redirecting the outcome from a JMS queue, we need a converter. If you’re using ActiveMQ like i you can use a “Message transformations”, but that has some drawbacks: The connection needs to be opened with a special header and what is worse, the Json generation is based on Jettison (which i cannot link anymore because the Codehause page stopped working) which is basically impossible to customize.

So instead, i assume there are ObjectMessages entering my queue (send through JmsTemplate to reach my service) and outgoing stuff should be in form of TextMessages. With that assumption, just use a slightly adapted MappingJackson2MessageConverter:

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
class Config {
  public SimpleMessageListenerContainer someServiceContainer(final SomeService someService, final ConnectionFactory connectionFactory) {
  	// Create an adapter for some service
  	final MessageListenerAdapter messageListener = new MessageListenerAdapter(someService);
  	// Connect the method [1]
  	// Direct every outcome of "someNonVoidMethod" to a topic, that is 
  	// subscribable via  stompClient.subscribe('/topic/some/response/topic', {});
  	// and take care of converting someResult to a JSON payload, otherwise we'll end up with a 
  	final MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter() {
  	  public Object fromMessage(Message message) throws JMSException, MessageConversionException {
  		  return message instanceof ObjectMessage ? ((ObjectMessage) message).getObject() : super.fromMessage(message);
  	  protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper) throws JMSException, IOException {
  		  final TextMessage rv = super.mapToTextMessage(object, session, objectMapper);
  		  rv.setStringProperty("content-type", "application/json;charset=UTF-8");
  		  return rv;
  	// [2] to a queue	
  	final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
  	return container;

This creates a configuration for creating a JMS Message Queue who’s outcome is send to a topic in the same format as Springs SimpMessagingTemplate would create, allowing to send messages to an arbitrary service whose return values are in turn passed (among others) to listeners on a WebSocket. This prevents manually connecting return values from a service to SimpMessagingTemplate, for example by injecting SimpMessagingTemplate into the service and manually calling convert and send. The service can therefore be a simple bean, not knowing anything about Spring, Jms, STOMP or Websockets.