First8 staat voor vakmanschap. Al onze collega’s zijn een groot aanhanger van Open Source en in het bijzonder het Java-platform. Wij zijn gespecialiseerd in het pragmatisch ontwikkelen van bedrijfskritische Java toepassingen waarbij integratie van systemen, hoge eisen aan beveiliging en veel transacties een belangrijke rol spelen. Op deze pagina vind je onze blogs.

JavaOne University – RESTful web services

Today is the first day of JavaOne 2015. Attendees were able to choose to attend the University Sessions in which a deep-dive was given in several topics or to attend several other sessions during the day. I started with the University Session “The Latest and the Greatest of RESTful Web Services”, given by Matt Heimer from Oracle. The goal of this course was to introduce us to the world of REST with JAX-RS. The course was divided into several chapters. Each chapter handles one subject, and a lot of items concerning the object. A lot of content was removed from the information to keep the blog concise and in an acceptable length. For example, interceptors, RESTful clients and JSON processing has been removed.

Part 1: Introduction to REST

Why do we need a web service? The answer to call a subroutine located in a different machine on a network. This can be done in several ways, for example RPC, .NET Remoting, CORBA/IIOP and RMI. Many remoting technologies are not fun to use or implement. They are either very complex or platform specific. A web service characterises itself by being platform neutral (including programming language), client-server architecture and (most likely) uses the HTTP as a transport protocol.

A web service client is coded to call operations on a remote server. The client must know which operations can be called on the server. In SOAP services this is done via the Web Service Descriptor Language (WSDL). A REST service can be described in several ways, you could use WSDL 2.0 but then you get the downsides of a SOAP web service.

Other ways of describing operations on a REST web service:

Characteristics of the two types of web services:

  • SOAP (JAX-WS, part of Java SE)
    • Heavily standard based which evolved over the years
    • XML data is transmitted across HTTP using POST requests
    • XML data lists the methods and parameters to call
    • XML response data is generated containing the method return data.
    • Closely tied to interface definitions (WSDL)
  • REST (JAX-RS, part of Java EE 6+)
    • Less formal and lightweight
    • Uses HTTP operations as method names (GET, POST, PUT etc.)
    • Each “resource” has its own URL
    • Can return either XML or JSON

Lets show REST web services!

This part shows various REST requests for a sample service. Our sample REST service contains multiple resources which can be linked.

  • HTTP GET http://localhost/REST-tryouts/resources/users – Retrieves a list of users. The collection is a resource.
  • HTTP GET http://localhost/REST-tryouts/resources/users/kelvin – One element of the collection is a resource.

Each resource should be a noun or thing and has a limited set of operations that it may support. These operations should be the request methods of the HTTP protocol. A resource is uniquely identified by the URL If resources should be nouns or things, how do you perform an action? The action that shouldeaxa be taken on a resource is defined by the HTTP operation called. In the examples below you can see that one resource can perform multiple operations based on the HTTP operation. There are rather simple examples.

  • HTTP GET http://localhost/REST-tryouts/resources/users/kelvin – This would GET user details.
  • HTTP PUT http://localhost/REST-tryouts/resources/users/kelvin – The body contains data to update the given user.
  • HTTP DELETE http://localhost/REST-tryouts/resources/users/kelvin –  Delete the given user from the system.

Let’s say you want to transfer money from me to Koen. You could call both resources (/users/kelvin and /user/koen) in which the body contains the amount of money to subtract and add to each account. The downside to this approach is that it is not atomical. A better approach would be to create a new resource which handles transfers (noun).  Let’s get back to an earlier example. When retrieving users from a system. You probably want to limit the amount of users or set a sorting order. This should be done with Query Parameters, not via additional resources.

  • HTTP POST http://localhost/REST-tryouts/resources/transfers – The body of this request contains the user identifications for both users and the amount of money to add or subtract. The web service then transfers money between the accounts in an atomic way (we hope).

Part 2: JAX-RS 1.1 RESTful Web Services

In this part we show Java code samples to implement the services. The next code is a very simple resource. The method getMessage() does not even have to be called that way, you can give it any name you want. As long as the @GET annotation is on the method JAX-RS will process a GET request. The above resource can be accessed with the url http://localhost/war/resources/message wherein war is the project name, resource is a default configuration in the Jersey Servlet. Message is the value in the @Path annotation. Each resource method has an annotation that is named after the HTTP method in full case.

But what if the client accepts only one specific content type? Then we write two or more @GET methods which produce different outputs. The client must call the server with the ‘Accept’ header filled with the content type it can understand. The server sends a Content-Type header to indicate the type returned. The @Produces annotation defines the content type returned. If there are multiple @GET annotation without the @Produces annotation, the server will return a 500 server error. It cannot decide which method to use.

The @Path annotation can also be added to methods. The annotation defines a path, following the @Path on the class for that specific method. This can be used, for example to retrieve a certain user.

If and when an error occurs on the RESTful web service, you want to report it to the client. Reporting an error to RESTful clients is simply a matter of returning the correct HTTP status code. What the correct code is, is entirely up to you. Take a look at the table above to see in which status code series the error should be. The code below returns a 404, or “page not found” response to the client.

JAX-RS can also handle WebApplicationExceptions, and sub-classes of it, to produce HTTP 400 or 500 status responses.

Part 3: JAX-RS 2.0 RESTful Web Services

In this final part of this post we will look at several changes, only affecting earlier mentioned functionality, that changes in JAX-RS 2.0 and will give a preview to the coming JAX-RS 2.1 and 2.1+ features.

  • Standard client-side API that was previously Jersey specific
  • Async processing
  • Filters and interceptors that were previously Jersey specific
  • Hypermedia improvements by adding Link modification in the header
  • Content negotiation
  • Common configuration

Asynchronous Processing enables more efficient use of processing threads.

  • Prevents blocking of processing threads
  • Supported in both client and server APIs
  • Server processing suspends the client connection and resumes it once a response is ready

The code below shows Server Asynchronous Processing

With JAX-RS 2.0 support for Bean Validation 1.1 (JSR-249) is introduced in environments which support Bean Validation. These validation constraints can be placed in the same location as @MatrixParam, @QueryParam, @PathParam, @CookieParam, @HeaderParam and @Context.

@POST
@Path(“{email}”)
@Consumes({“application/x-www-form-urlencoded”})
public void performTask(@NotNull @Email @FormParam(“email”) String email) {
//..
}

When a validation error occurs a javax.validation.ValidationException or subclass is thrown. Jax-RS implementations must include an exception mapper which maps ValidationException to either 400 or 500 status codes.

In conclusion

The entire session took well over 7 hours in total. In those 7 hours more information was given on each topic with more in-depth view and features not present in this blog. I enjoyed the session and really liked the way Matt Heimer talked about the topics. He also took the time necessary to explain several other items, which had nothing to do with REST but gave us a better understanding of some inner workings. I would highly recommend to attend session given by Matt.

Having mainly written SOAP web services, I got tired of all the boilerplate. It’s highly likely that for my next web service I would use a REST approach.