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;
cell.contentDisplayProperty().bind(Bindings.when(editingProperty())
                    .then(ContentDisplay.GRAPHIC_ONLY)
                    .otherwise(ContentDisplay.TEXT_ONLY));

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.editableProperty().bind(column.editableProperty());
	this.colorPicker.disableProperty().bind(column.editableProperty().not());
	this.colorPicker.setOnShowing(event -> {
	    final TableView<T> tableView = getTableView();
	    tableView.getSelectionModel().select(getTableRow().getIndex());
	    tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);	    
	});
	this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
	    if(isEditing()) {
		commitEdit(newValue);
	    }
	});		
	setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }
 
    @Override
    protected void updateItem(Color item, boolean empty) {
	super.updateItem(item, empty);	
 
	setText(null);	
	if(empty) {	    
	    setGraphic(null);
	} else {	    
	    this.colorPicker.setValue(item);
	    this.setGraphic(this.colorPicker);
	} 
    }
}

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?

| Comments (21) »

27-Oct-14


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: github.com/michael-simons/bikingFX.

That is what it looks like:

bikingFX1

bikingFX2

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:

Given

@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 
viewBikes.setItems(bikes);

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
viewBikeBoughtOn.setCellFactory(LocalDateTableCell::new);

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.

Deploying

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.

Mobile?

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.

Conclusion

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.

| Comments (9) »

22-Oct-14


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;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 
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() {	    
        filter(Projekt_.lieferjahr)
            .with((cb, p, value) -> cb.like(cb.function("to_char", String.class, p, cb.literal("YYYY")), value + "%" ))
        .filter(Projekt_.angelegtAm)
            .with((cb, p, value) -> cb.like(cb.function("to_char", String.class, p, cb.literal("DD.MM.YYYY")), "%" + value + "%"))
        .filter(Projekt_.anwender, Anwender_.name)
            .with((cb, p, value) -> cb.like(cb.lower((Path<String>)p), "%" + value.toLowerCase() + "%"))
        .filter(Projekt_.marktteilnehmer, Marktteilnehmer_.name)
            .with((cb, p, value) -> cb.like(cb.lower((Path<String>)p), "%" + value.toLowerCase() + "%"))
        .filter(Projekt_.versorgungsart)
            .with((cb, p, value) -> cb.like(cb.lower((Path<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;
 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
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;
import org.springframework.data.jpa.domain.Specification;
 
@FunctionalInterface
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 org.springframework.data.jpa.domain.Specification;
 
import static java.util.stream.Collectors.reducing;
 
public class FilterSpecification<T> implements Specification<T> {
 
    protected final Map<PathOperation, PathAndValue> filteredPaths;
 
    public FilterSpecification(Map<PathOperation, PathAndValue> filteredPaths) {
        this.filteredPaths = filteredPaths;
    }
 
    @Override
    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()))
            .collect(
                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 java.util.stream.Collectors;
import javax.persistence.metamodel.SingularAttribute;
import org.springframework.core.MethodParameter;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
 
public class FilteringSpecificationArgumentResolver implements HandlerMethodArgumentResolver {
 
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(FilterDefinition.class) && parameter.getParameterType() == Specification.class;
    }
 
    @Override
    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 “marktteilnehmer.name” 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.

| Comments (13) »

24-Sep-14


Mockito#validateMockitoUsage

Hi, long time no see… I really had a lot of work to do, been doing some freelance work in the nighttime and then there’s certainly my family. And apart from that, my current setup for this years projects is working quite well, thanks to Spring Boot and NetBeans for example.

Recently i had some failing tests. I used to Mockito to verify method calls and though i was sure the tested code was correct, the test kept failing.

What was wrong? The verification of calls run before the next mock. So what was failing was the previous test and I was too stupid to see the navigable exception at first (and second…).

To avoid this behavior and make the test fail that actually fails verification, add the following to your test class:

@After
public void validate() {
    Mockito.validateMockitoUsage();
}

or run your test with the MockitoJUnitRunner.

Read some about this behavior in the Mockito API: Mockito.validateMockitoUsage.

| Comments (0) »

12-Sep-14