Custom REST Links with Jersey Conditional Link Injection

The "RE" in REST stands for "Representational", with "State Transfer" completing the acronym. In this post we'll look at using Jersey to conditionally inject custom links in our REST Resources.

In the User Service of our NixMash Microservices app we're serving up the following JSON for our User. First our user list where we are providing a link to the individual User data in link.

We add a few custom links in our User record, one to "self" in link, one to the User list with a "parent" relation and a link to the application root, relation "home."

Jersey Conditional Link Injection

There are several approaches to building custom links, one of which is to create annotated Representation Entity classes for each State of the Resource. That approach gives us the most flexibility, with a clean POJO and annotations in the Representation Entity classes. That's a bit more code than we want to do now, so for simplicity's sake we're going to annotate the POJO itself.

Because we're annotating the POJO and using a single class for both List State and the Individual Record we need a way to prevent the above "parent" and "home" relation links from appearing on the List output. We do that with Jersey Conditional Link Injection.

Here is our "users" link annotation which we want to display on the individual record only.

Notice the @InjectLink condition and the Java Expression Language ${instance.showUsersLink}. There's a lot we can do with EL here. What we're going to do is use a showUsersLink property in the POJO as our condition value.

We set that property to TRUE in the Resource individual User Get(id) method which keeps things real simple, otherwise it is false.

Testing the Injected Links

Our tests are pretty simplistic as well. We call the GetAll() and Get(id) methods confirming each User's ShowUserLink status based on the List or Individual Record State of the User Resource.

Source Code Notes for this Post

Source code discussed in this post is found in NixMash Microservices on GitHub. Code for this particular post is found in branch microservices-v0.1.0 – Initial Layout and Structure.