September 6, 2012

Not using Spring Data yet? Well, you should, and here's why.

In pretty much every single project you will ever work in there will be a need to persist data. Typically you will use things like JPA, Hibernate, and similar APIs. Using these APIs is a huge step forward compared to the good ol' days when we didn't have things like O/R mappings and nice transactional APIs but had to fiddle around with JDBC connections, rolling back transactions, reading from result sets and whatnot.1 But still, pretty much all of the work you do every time you create a repository class for your entities is plumbing. You are creating nothing but boiler plate code. And time spent on boilerplate code is time wasted, because you are writing code that adds no real value but still needs to be tested and maintained.

July 3, 2012

Mockito: Default values and how to get more out of them

The problem

A while ago I had an interesting discussion with two of my colleagues, Dan Bergh Johnsson and Daniel Deogun, about how to change the default return value of unstubbed methods in Mockito. The background for the discussion was that by default, Mockito returns default values for unstubbed methods and these default values are usually good enough. In some cases that default value will be null and if the code being tested tries to use the returned null value it will cause a nullpointer exception. The stack trace of that exception will quite easily give away that the cause was an unstubbed method.

However, if the tested code calls an unstubbed method and, instead of using the null value directly, stores it and uses it later. Then the stack trace of the nullpointer exception will no longer reveal that the cause was an unstubbed method but will point to some random code line that can be far away from where the unstubbed call actually took place. When this happens it usually takes some time to figure out what the root cause was. Lets take a look at how we would approach this situation and how we can get a more informative error when it occurs.

May 24, 2012

Scala + Spring MVC = True? (Part 3)

This is the third part in a series of articles about mixing Scala and Spring MVC. In the first post we looked at how to set up a Scala-Java Maven project and we saw how well Spring MVC translates over to Scala in a very simple example. In the second post we created a web service that returned JSON data using the Jackson JSON processor and we looked at how we can use both Java and Scala to get the job done.
In this third and last post of our Spring MVC and Scala experiment we will continue to work on the web application that we used in the previous posts so you might want to get the example code on GitHub so you can try out the examples on your own as we go along.

JSR-303 Validation

Another very common use case when building web services is the use of JSR-303 Bean Validation for validating input data. Lets take a look on how the Spring MVC support for JSR-303 will work together with Scala by adding some more functionality to our web service.

April 27, 2012

Scala + Spring MVC = True? (Part 2)

This is the second part in a series of articles about mixing Scala and Spring MVC. In the first post we looked at how to set up a Scala-Java Maven project and we saw how well Spring MVC translates over to Scala in a very simple example. In this post we will continue with our exploration of Spring MVC and Scala by extending our web application that we started on in the previous post so you might want to go get the example code on GitHub so you can follow along.

Jackson JSON Processor

Lets continue our example by turning our web application into a web service returning data in JSON format. Maybe it will even grow up and be a RESTful web service someday. The typical framework of choice for processing JSON in a Spring MVC application is the Jackson JSON Processor.

April 18, 2012

Scala + Spring MVC = True?

This is the first part in a series of articles about mixing Scala and Spring MVC. In this post we will start by setting up a Maven project that can handle a Scala-Java mixed project and then we will take a look at a simple example of a web service using both Scala and Spring MVC.

Scala, is a language that has a lot of benefits and some nice characteristics and there are more and more companies that are starting to use it in their production code. Unless you have the privilege to build a brand new system all in Scala, and that new system have no need to integrate with any other code base, you will sooner or later find yourself facing issues around mixing Java and Scala code together if your current systems are written in Java. Spring MVC is a well known framework and is extensively used in a wide variety of applications and chances are you already have a well functioning Spring MVC application. Maybe you also have a lot of infrastructure build around it and integrated to it, like access control and logging for example. And since that infrastructure is written in Java you need to be able to take advantage of those available systems to make the most out of your Scala API.

Ok, so all you need to do is hook up your new shiny Scala API that you have developed. But how do you do it? And does it work? Those are some of the questions that I asked myself and I will try to share some of my findings on the subject here.

April 4, 2012

Take your REST API to the next level with HATEOAS

A pragmatic approach to understanding HATEOAS

HATEOAS, or "Hypermedia As The Engine Of Application State", is a lot about the discoverability in a RESTful API. And it is also the part that most REST APIs misses out on. This is sad because there are a lot of benefits to reap if you take your API to the next level. Especially for the developers using your API.

Some of the benefits of using HATEOAS include simpler clients, simplified authorization control on the client side, and making your API self-documenting. If you are all new to the concept then Martin Fowler's article on the RESTful maturity model is a good start. To summarize it, the model defines four levels of maturity of the RESTfulness of an API:
  1. One URI, one HTTP method
  2. Multiple resources instead of a single endpoint
  3. Use of HTTP verbs
  4. Discoverability by using hypermedia
This model can help us understand the ideas behind REST and to fully experience the "glory of REST" the API must pass all four levels. The last level is what HATEOAS is all about and I will spend the rest of this post to discuss a somewhat pragmatic approach to how you can bring HATEOAS to your REST API.* Before we move on it is also worth mentioning another good article about the topic written by Rickard Öberg that you also might want to check out.

March 20, 2012

Controlling message converters with Spring MVC 3.1

In my previous post I talked about how to support both JSON and XML in a Spring MVC web service. The observant reader might have noticed that if a request was made with an Accept header with neither application/json nor application/xml specified then the data was returned in XML. The integration test in the example code used to illustrate this looked like this:

 public void getUserWithUnsupportedAccept() throws Exception {
  RestTemplate restTemplate = createStringRestTemplate();

  String user = restTemplate.getForObject(new URI(baseUrl + "/123"), String.class);

  logger.debug("Received data as: {}", user);

The code will log the received data and you can see that it is in XML format. The reason for this is how the message converters are added by default. Go check out the Spring source code if you want to know the details.

Now, if you rather want JSON to be the default format then changing the behavior of our web service is simply a matter of defining our own order for the message converters and make sure the JSON converter comes before the Jaxb converter.

March 14, 2012

Combining JSON and XML in RESTful web services with Spring MVC

There are occasions when you need to support multiple representations of the same resource in a REST API. For example, a smartphone client might want the resource to be represented in JSON while your B2B partner's application that is integrating through your API wants the representation to be XML.

Willie Wheeler wrote an excellent blog post about how to support both XML and JSON from a web service endpoint using the new features of the @RequestMapping annotation in Spring 3.1. The example in the blog post, by intention, uses two different URLs for the two different representations.

However, when dealing with RESTful services the preferred approach to design your API would usually be to have a single URL for the resource regardless of what representation the requesting client is asking for. A way to solve this is to let the requesting client specify what representation it prefers via the Accept header in the HTTP request. The server will examine the request header and send back the resource in the proper representation. This can very easily be implemented by using Spring MVC and I figured I will show you how this can be accomplished with the following example.