Skip to content

Category Archives: Java

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.

Custom editor components in JavaFX TableCells


There’s a lot of confusion about custom editor components in TableCells for JavaFX applications. The problem: Someone (like me) implements a custom TableCell with a DatePicker or a ColorPicker for example. A naive solution maybe looks like this.

That works in so far that the value is correctly displayed in the ColorPicker and the ColorPicker is active and can be changed. But, given that the cell is editable, the property of the cells item is editable, the value of it never changes, regardless what is selected in the ColorPicker.

You’ll find a lot of tips like this or this. They have in common that they are either rather complex and most of the time uses a stanza like this:

TableCell cell;

Although pretty cool feature that bindings can be conditionally expressed, but not so useful. What is stated there is: “If the table is not in editing mode, use the text set with setText (in that case a formatted date), otherwise, if editing mode, use the node provided through setGraphic”. So the date picker in that case or my color picker is only available when editing. What might work with a date picker isn’t an option with the color picker. Also, the user need to do 2 clicks.

So i came up with that solution:

public class ColorTableCell<T> extends TableCell<T, Color> {    
    private final ColorPicker colorPicker;
    public ColorTableCell(TableColumn<T, Color> column) {
	this.colorPicker = new ColorPicker();
	this.colorPicker.setOnShowing(event -> {
	    final TableView<T> tableView = getTableView();
	    tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);	    
	this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
	    if(isEditing()) {
    protected void updateItem(Color item, boolean empty) {
	super.updateItem(item, empty);	
	if(empty) {	    
	} else {	    

Let me explain:

  1. this.colorPicker.setOnShowing() adds a handler that is executed just before the color picker popups up. It retrieves the TableView from the cell and also the currently selected row (which only works in single selection mode). It than starts the edit by calling tableView.edit. There’s no need to call startEdit() from TableCell, which actually will lead to a NPE somewhere…
  2. Than i watch the valueProperty() of the color picker and not the onAction or keypressed or whatsoever event, i want the value. That value is then committed. All further actions on the table are automatically, no need to manually call updateItem and the like.

That solution can be easily transferred to LocalDate cells etc. It’s benefits: It’s trivial and easy to implement, better user experience (no vanishing controls, no 2 clicks). Everything that fiddles with setContentDisplay(text or graphic) is just working around to get the table into edit mode when the user clicks often enough.

The classes shown here are part of my JavaFX demo project BikingFX, which is available on GitHub.

What do you think?

Getting started with JavaFX 8: Developing a REST client application from scratch


It was was mid 2013 when i first tried to run the JavaFX samples under OS X, in fact, there’s still a draft post around here in which i wanted to describe the steps necessary to run that stuff with ant and how to use Maven to build an app.

Well back then i played around a little with JavaFX 2.1 but all that fiddling around including jfxrt.jar and such wasn’t much fun.

1,5 years forward i’m sitting in various conference rooms in San Francisco, enjoying JavaOne 2014 sessions.

I’ve seen two interesting JavaFX 3D sessions with respectively bye Sean Phillips and especially inspiring “Swing Away! Move to JavaFX 8 and the NetBeans Platform” by Gail and Paul Anderson.

My personal background: I’ve been creating Java Swing applications since 2004 now and we have one very graphic heavy GIS application and also many form based stuff, so there’s some background developing Java client applications.

I got myself Pro JavaFX 8 by Johan Vos, Weiqi Gao, Stephen Chin, Dean Iverson and James Weaver as well as Javafx Rich Client Programming on the Netbeans Platform by the Andersons, the later one didn’t arive in time for my experiments, so review here.

So give something to code. Why not reusing the topic from my series of posts Developing a web application with Spring Boot, AngularJS and Java 8, which had gotten quite some attention of the last months.

The app is build around a REST api that is currently used by an AngularJS frontend for the webpage.

My goal was to create a client application that:

  • Displays all biking pictures, shuffles and flips them
  • Displays all bikes and makes them editable
  • Displays all gallery pictures (and in the future, also allows to upload some)

That gave me the following topics: Getting and processing JSON (i could have used Jackson again, but i decided for JSR 353), creating a basic JavaFX layouts using Scene Builder and connecting it to stuff, loading other stuff in the background so that the GUI won’t block, show progress.

The code for the this app named “BikingFX” is on github:

That is what it looks like:



The pictures in the upper row are randomly selected and flip around with a nice transition, the pictures in the table are lazily loaded. As added bonus, some table cells use specialized input fields (Date- and ColorPickers).

ProJavaFX gives you a real good start with JavaFX. At first, the authors give a brief history about JavaFX (which i find quite interesting) and than starts with the coding. The examples are all based on NetBeans projects and are available online, they work as advertised and are thoroughly explained in detail. Very nice.

All the topics i was interested are there: “Getting a Jump Start / Creating a User Interface”, very important “Properties and Bindings” (make sure to read this, Properties are the based thing that could happen to Java client GUIs, no more need for JGoodies, sorry; and Bindings are a great way to control computations and such), than “Collections and Concurrency”.

The chapter about UI Controls is missing some information about editable cells, but that can easily be retrieved from the API.

Overall, the book ProJavaFX 8 is a joy to work with. Didn’t notice any errors so far, the language is good, really nothing to complain.

I will show you some aspects of the little application, i’ve developed:

It took me approximately 24 hours in total to get there.

Getting JSON data into the client

JSON data for my application will be from an online api so that must run in the background and not in the JavaFX application thread. The heart of the javafx.concurrent framework is the Worker interface with it’s three abstract base classes, Task<V>, Service<V> and ScheduledService<V> from which i use Task and ScheduledService in my program.

Retrieving lists of stuff in my application is a one time Task and so i used just that:

Notice the use of new Java 8 features, namely the ObjectFactory as a functional interface and the actual call() method where a method reference for a method on a concrete object is used to call constructors as factory methods that use the JSONP api like this:

The task provides no public constructor but a static getter that handles all the stuff to instantiate an ObservableList and fill it with stuff when the API call is finished.

The observable collections together with bindings makes creating tables with dynamic data in JavaFX so sweet. Putting those things together is just something like this:

“viewGalleryPictures” is an attribute of “TableView” which is injected via @FXML into my root controller:

All layouting took place in Scene Builder (by the way, separating that program code from the actual layout in FXML is by far the best solution for any GUI builder and one that actually works without constraints on source code).

In the snipped above you notice a constructor method reference. That stuff is really powerful and I hardly know what i did without it before Java 8. It allows changes like this “Replace specialized task with a generic one” and this.

Observing stuff

You can literally observe everything in a JavaFX application.

First of all there all the nice observable collections, in my case for example a list of BikingPictures that are loaded via the above JsonRetrievelTask. If they are finished loading, it’s time to actually load the image data and display it, so i observe the content of the list:

The event actually contains a list of changes but here i am only interested wether the list has actually elements or not.

There is also an HBox inside the root layout which is inject as bikingPicturesContainer into RootController. HBox is container element that lays out its children in a single, horizontal row and is used for the header of biking pictures in my app.

I observe its width with a listener (which would have been written as an anonymous, inner class pre Java 8):

Every time the main window gets resized, the listener is notified and uses #loadPictures to randomly select entries from #bikingPictures and then load them using an Image. I could have used an ImageView, but i wanted to observe the progress of the ImageLoading as well so that i can but a ProgressIndicator as a placeholder in my container and swap it when the image is ready:

If i had used the URL constructor from ImageView i would have ended up with an unresponsive UI, as it loads the images on the JavaFX application thread.

Using background services

Tasks are things that are usable once, services are for reoccurring tasks. For every execution they must generate a new task and so does my FlipImageService. That service is actually a ScheduledService and without much ado one can #start() it and has a periodically task.

The special service selects and loads one of the available pictures (that are does that aren’t showing at the moment):

loads an Image (this time immediately, notice the last boolean parameter):

If this succeeds, it picks on the JavaFX application thread one of the elements in the HBox mentioned above and exchanges it’s contains with a “flip” animation that consists of two ScaleTransitions:

Present and edit stuff in tables

Many applications deal with presenting and editing data in tables, so does this application.

All my beans are perfect JavaFX beans, that is: Their attributes are implemented as Properties, with final value getters and setters and corresponding xxxProperty() assessors, for example take a look at the Bike class.

To get them into a table is just a matter of few lines:


@FXML private TableView<Bike> viewBikes;
@FXML private TableColumn<Bike, String> viewBikeName;
@FXML private TableColumn<Bike, Color> viewBikeColor;
@FXML private TableColumn<Bike, LocalDate> viewBikeBoughtOn;
@FXML private TableColumn<Bike, LocalDate> viewBikeDecommissionedOn;
@FXML private TableColumn<Bike, Integer> viewBikeMilage;

and fill like so

# Get an observable list of bikes that will contain them when loaded
final ObservableList<Bike> bikes = JsonRetrievalTask.get(Bike::new, "/bikes.json?all=true");
# Set this as the item source of the table 

Then, bind the properties of the JavaFX bean

viewBikeBoughtOn.setCellValueFactory(new PropertyValueFactory<>("boughtOn"));
# and optionally configure the cell factories (or cell renderers for all the Swing people out there

Feels way more natural than the “old” Swing Tablemodels.

The dates of a bike and the color need some nice representation. That was quick to implement, thanks to the already existing components DatePicker and ColorPicker (Find exhaustive information about most components available in ProJavaFX). It’s straight forward to use them as table cells:

You’ll notice that the constructor takes a column parameter. I need that for two things: Bind the editable property of the column to the editable property of this cell (with that solution, all cells are either editable or not, this cell implementation cannot be used for individually editable cells). The component is the mentioned DatePicker, which also is instantiated together with a custom format inside the constructor.

The actually rendering is done by update item. This method can be called very often so it’s important that this part is fast, therefore the stuff gets initialized inside the constructor. The docs for TableCell clearly states that calling super.updateItem is a must, also setting text and graphic to null if the cell is empty. The rest is just logic to use just a text when the cell isn’t editable and the date picker if it is.

Going back to the specific constructor signature: It can be used as a Callback for TableColumn#setCellFactory(LocalDateTableCell::new). The callback is called every time a new cell is needed. Doesn’t the constructor reference looks much nicer than a factory class or anonymous inner class implementation of the interface linked above?

At the moment, the server side is missing update features for decommissioning bikes and the bike color but i can add respectively set the current mileage of a bike, so i implemented that.

As i mentioned above, the Beans are all full JavaFX beans so any change in the TableCell is directly propagated to the bean itself. Therefor i’ve registered my handler to the properties i’m interested in on every bean whenever the list of bikes changes like that:

That is also a nice example of how to traverse the list of changes to a given collection.

The actual handler, MilageChangeListener, looks like this:

Again, what we see here is a task being spawned when the value of the cell changed. That task calls the rest API and updates stuff by calling a protected REST method, setting the appropriate authorization on the connection. Also shown here is how to POST body data to an endpoint. The connection must be told to do in- and output and than output can be written to the connections output stream. Again, i use the JSONP api.

What i actually don’t like about that solution is the fact that if the entered value is wrong, i cannot reliable reject an invalid change and the value stays in the table cell and the bean. If i would set the value back to the old value, than the listener will fire again immediate.

Notice two additional things:

Those are functional interfaces which are implemented by RootController#retrievePassword and RootController#storePassword and again, passed as method references when instantiating the listener in line 150:

final MilageChangeListener addMilageController = new MilageChangeListener(this::retrievePassword, this::storePassword, this.resources);

Pre Java 8 you would have to either pass a reference to the full controller around or introduce some more or less useless interfaces.


After all that years, i’m still a big fan of Maven. The memory of projects deployable only on one machine (when the moon is full etc.) still hurts. When i tried JavaFX last for the first time, that wasn’t actually going well, but those problems are gone as well. If you like, NetBeans creates a Maven JavaFX project for you that works right out of the box. For development it isn’t even necessary to add the jfxrt.jar as dependency, but the Maven compiler plugin needs it. Luckily it is contained now since some Java 7 version in the JRE/JDK and it is as easy as that:

to add it. No more mudding through system dependencies and such.

It has become remarkably easy to create single-jar applications and also native bundles with JavaFX and maven. The above configuration just does this, creating a single-jar (which is really small, with the one dependency (JSONP api and implementation) not much above 120k). I’ve added a second profile called installer which get’s activated during package phase with the property -DcreateInstaller=true and creates installer bundles inside target for the current platform.

That works reliable under OS X, Windows (7) and Debian, tested so far. The bundles for OS X gets a lot bigger than for Windows as the javapackager includes the whole JDK instead of the JRE on that platform so what was just about 100k becomes a hefty 170M. Anyway, that are the steps in the right direction.


With the JavaFX 8 ensemble hitting the Google Playstore just this week and being available in the Mac App Store for quite some time now i was hoping there is a relatively easy way to get this thing running on either one of my Android or iOS devices, but as i used plenty of Java 8 features, that isn’t possible at the moment. Neither RoboVM nor the JavaFX on Android community support Java 8 at the moment, but I’m sure that’s gonna change, especially in the light of the announcement that RoboVM and LodgON will team up to bring JavaFX to both mayor mobile platforms: JavaFXPorts.


I think I’m doing that stuff long enough to know when something feels just right. Apples swift is a nice thing if you only want to do Apple related stuff, so is the Android SDK.

But with my language knowledge of Java i can truly achieve “write once, run everywhere” using JavaFX. JavaFX compared to Swing is a real breath of fresh air and also, really needed. The controls looks great, even with their default theme and I didn’t even get started to skin them using CSS (which is beyond me, you just need to look at this site ;)).

If you’re into that stuff, get yourself a copy of ProJavaFX 8 for a solid and comprehensive overview of the terminologies and technologies used. If you’re assignment is to create a form based applications with a lot of dialogues, forms and menus i recommend the Javafx Rich Client Programming on the Netbeans Platform guide. As always, read the API, those docs are full of information and actually useful examples (for example on who to watch progress on a task from the platform thread). Last but not least there’s Oracles Getting Started with JavaFX with a lot of working examples.

Writing this application and this post gave me the same feeling of having made the right decision many years ago betting on Java as writing that post and the application. Java looked dated just before the Sun acquisition but that changed a lot and this years JavaOne motto “Create the future” seems actually be possible.

Creating Specification<> instances for Spring Data JPA with Spring MVC


One common requirement in web applications is to be able to filter a given set of data through request parameters. One way to do this is fetch everything from the server and filter it on the client. Me, i’m more of a server guy and i tend to do this inside a database.

Many projects of mine are developed with JPA based beans for the data model and recently i’ve come to really love Spring Data JPA. With the plain declaration of an interface extending a repository interface, you get everything you need to query your domain. Through in a second interface and you can execute JPA based criteria queries:

import entities.Projekt;
public interface ProjektRepository extends JpaRepository<Projekt, Long>, JpaSpecificationExecutor {    

My goal: Create controller methods for Spring MVC like so

@RequestMapping(value = "", method = GET)
public Page<Projekt> getProjekte(
    final @RequestParam(defaultValue = "0", required = false) int page,
    final @RequestParam(defaultValue = "10", required = false) int pageSize,	    
    final @RequestParam(required = false, defaultValue = "lieferjahr") String orderBy,
    final @RequestParam(required = false, defaultValue = "ASC") Direction orderByDirection,
    final @FilterDefinition(paths = FilteredPathsOnProjekt.class) Specification<Projekt> filter	    
) {
    return this.projektRepository.findAll(filter, new PageRequest(page, pageSize, new Sort(orderByDirection, orderBy)));

where the filter parameter is of type Specification and where i can define which fields are to be filtered in which way in a type-safe way that is checked on compile time like so:

public static class FilteredPathsOnProjekt<Projekt> extends FilteredPaths<Projekt> {
    public FilteredPathsOnProjekt() {	    
            .with((cb, p, value) ->"to_char", String.class, p, cb.literal("YYYY")), value + "%" ))
            .with((cb, p, value) ->"to_char", String.class, p, cb.literal("DD.MM.YYYY")), "%" + value + "%"))
            .with((cb, p, value) -><String>)p), "%" + value.toLowerCase() + "%"))
            .with((cb, p, value) -><String>)p), "%" + value.toLowerCase() + "%"))
            .with((cb, p, value) -><String>)p), "%" + value.toLowerCase() + "%"));		

I found this very inspiring post An alternative API for filtering data with Spring MVC & Spring Data JPA by Tomasz and here again, i big thank you.

My solution is similar, but uses the JPA Metamodel API that generates a metamodel from the annotated entity classes. In the above example, the entity is Projekt, the metamodel Projekt_ that lists all attributes that are mapped from the database.

Let’s start with the controller. Parameter filter is of type Specification and is annotated with @FilterDefinition:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public @interface FilterDefinition {
    Class<? extends FilteredPaths> paths();
    Class<? extends FilterSpecification> implementation() default FilterSpecification.class;

I need to wrap the paths i want to filter with a class because only are small list of types are allowed in annotations. The class looks like this:

import java.util.List;
import java.util.Map;
import javax.persistence.metamodel.SingularAttribute;
public abstract class FilteredPaths<T> {
    protected final FilteredPathsBuilder<T> builder = new FilteredPathsBuilder<>();
    public final Map<List<SingularAttribute<?, ?>>, PathOperation<T>> getValue() {
        return this.builder.getFilterablePaths();
    protected FilteredPathsBuilder<T> filter(SingularAttribute<?, ?>... path) {
        return builder.filter(path);

The core of this is the getValue method. It returns a map of lists of SingularAttributes (a list of them to do queries on sub elements) and a PathOperation. PathOperation is a functional interface:

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
public interface PathOperation<T> {
    public Predicate buildPredicate(CriteriaBuilder cb, Path<?> path, String value);

that is used by my FilterSpecification to build the predicate:

import java.util.Map;
import java.util.function.Function;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import static;
public class FilterSpecification<T> implements Specification<T> {
    protected final Map<PathOperation, PathAndValue> filteredPaths;
    public FilterSpecification(Map<PathOperation, PathAndValue> filteredPaths) {
        this.filteredPaths = filteredPaths;
    public final Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        this.customizeQuery(root, query);
        return this.filteredPaths.entrySet().stream()
            .map(entry -> entry.getKey().buildPredicate(cb, entry.getValue().getPath(root), entry.getValue().getValue()))
                reducing(cb.conjunction(), Function.<Predicate>identity(), (p1, p2) -> cb.and(p1, p2))
    protected void customizeQuery(Root<T> root, final CriteriaQuery<?> query) {

As you see there’s one big difference to Tomasz solution: I don’t support OR’ing the filters, i’ve only support AND. I like the way i can use the Java 8 stream api and the reduction method to add them together very much.

How get’s this class instantiated? Here come’s the additional Spring MVC argument resolver:

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.persistence.metamodel.SingularAttribute;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
public class FilteringSpecificationArgumentResolver implements HandlerMethodArgumentResolver {
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(FilterDefinition.class) && parameter.getParameterType() == Specification.class;
    public Object resolveArgument(
        MethodParameter parameter,
        ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest,
        WebDataBinderFactory binderFactory
    ) throws Exception {
        final FilterDefinition filterDefinition = parameter.getParameterAnnotation(FilterDefinition.class);	
        final FilteredPaths<?> paths = filterDefinition.paths().newInstance();
        final Map<PathOperation<?>, PathAndValue> filterValues = new HashMap<>();
        paths.getValue().entrySet().forEach(entry -> {
            final String param = entry.getKey().stream().map(SingularAttribute::getName).collect(Collectors.joining("."));
            final String paramValue = Optional.ofNullable(webRequest.getParameter(param)).orElse("");
            if (!paramValue.isEmpty()) {
                filterValues.put(entry.getValue(), new PathAndValue(entry.getKey(), paramValue));
        return filterDefinition.implementation().getConstructor(Map.class).newInstance(filterValues);

It supports controller arguments of type Specification annotated with @FilterDefinition. To resolver the argument it gets the annotation and then instantiates the class that holds the lists of paths that should be filtered. The lists actually contains the path and the filter operation. It’s iterated and each list of singular attributes is joined together with a “.”, so one attribute becomes “versorgungsart” and a nested becomes “” for example. It then checks the web requests if there are request params with those names. If so, the filter operation is added together with the path and the value for that path (from the request) to a new map (the operations are the key). This map than is passed to the implementation of the Specification.

What’s nice here: I don’t need to check if the attributes that are requested from the outside exists. As i start with the attributes of the entity from the start, there’s no chance i try to access one that doesn’t exists.

What’s missing is the pair type PathAndValue

import java.util.List;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
public class PathAndValue {
    private final List<SingularAttribute<?, ?>> path;
    private final String value;
    public PathAndValue(List<SingularAttribute<?, ?>> path, String value) {
        this.path = path;
        this.value = value;
    public String getValue() {
        return value;
    public Path<?> getPath(final Root<?> root) {
        Path<?> rv = root;
        for (SingularAttribute attribute : path) {
            rv = rv.get(attribute);
        return rv;

that not only holds both the path (as a list of attributes) to be filtered and value to be filtered with, but also generates a complete JPA criteria path that is given to the PathOperation.

And last but not least is the little FilteredPathsBuilder that allows me to write the filter definition in a readable way and not obstructed with map and list operations as shown in FilteredPathsOnProjekt above:

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.metamodel.SingularAttribute;
public class FilteredPathsBuilder<T> {
    private final Map<List<SingularAttribute<?, ?>>, PathOperation<T>> filterablePaths = new HashMap<>();
    private List<SingularAttribute<?, ?>> lastPath;
    private PathOperation<T> lastOp;
    public FilteredPathsBuilder<T> filter(SingularAttribute<?, ?>... path) {
        if(lastPath != null && lastOp != null) {
            filterablePaths.put(lastPath, lastOp);	    
        this.lastPath = Collections.unmodifiableList(Arrays.asList(path));
        this.lastOp = null;
        return this;
    public FilteredPathsBuilder<T> with(PathOperation<T> op) {
        this.lastOp = op;
        return this;
    public Map<List<SingularAttribute<?, ?>>, PathOperation<T>> getFilterablePaths() {
        if(lastPath != null && lastOp != null) {
            filterablePaths.put(lastPath, lastOp);	    
        this.lastPath = null;
        this.lastOp = null;
        return Collections.unmodifiableMap(filterablePaths);

As you can see in FilteredPathsOnProjekt above i have now a little DSL that i use to define which attribute of my entity should be filtered. Writing down the PathOperation as lambdas and using the generated MetaModel to specify the attributes i have not only filters that are checked on compile time but also have the the attributes definition only in one place. All solutions that require writing down lists of request parameters or fiddling with map parameters are too error prone and in the end, way too much work to write.

The above solution works fine with Spring 4.0.x and 4.1.x and certainly with Spring Boot. I’ve got tests for all of the code above and should anyone find this solution useful, i’m gonna prepare a standalone project with it.

Let me know, what you think.