Some days ago i had to face up a problem that probably more developers had to solve but for which not many of them can answer to me. My prolem was to generate a simple client from a Java Interface annotated with JAX-RS annotations.

From a design pattern point of view what i need was a Proxy. I want to emphasize this aspect because finding the key words of a problem is very important to search the solution. So, the good news is that exists a working solution, the bad news is that there is no standard method that implements it, because JAX-RS provides good Client API and you have to implement your client every time you need it.
Resteasy is a framework developed by JBoss and will help us to generate a client from a JAX-RS Java interface.

Resteasy can be compared to framework like Jersey or Apache CXF, all of them implement the JAX-RS standard and all of them solve the same problems, but some of them provide some features to make the devlopment easy and enable us to save a lot of time.

As all we know JAX-RS provides some annotations to generate a Rest Service from a Java interfacce, for example with the interface shown below we can implement a REST Service that has two operations mapped with a GET, a PUT method:

public interface RestService
{
   @GET
   @Path("get")
   @Produces("text/plain")
   String get();

   @PUT
   @Path("put")
   @Consumes("text/plain")
   void put(String body);

}

If we had to develop a client we should create an http client and invoke an URL for each REST operation we want to invoke, furthermore we have to read the status code of the response and deserialize the payload.
Yes we can do this or we can use Resteasy Proxy Framework , this client framework will help us to do all the steps described above.
So if we want to generate the rest proxy we have to use Resteasy with this code snippet :

Client client = ClientFactory.newClient();
WebTarget target = client.target("http://example.com/base/api");
ResteasyWebTarget rtarget = (ResteasyWebTarget)target;

RestService service = rtarget.proxy(RestService.class);
service.put("hi,  i'm invoking RestService in a simple way");

The core of this code is the proxy method. What we have done is to pass the service interface to the proxy method to get a working http client. Now we can use the interface methods to invoke the service, each invocation will trigger an http request with headers, path parameters and payload, mapped with the JAX-RS annotations. In other words we have got the mirror opposite of the JAX-RS server-side.

A great
rest
client to all :)



  • submit to reddit
blog comments powered by Disqus