Seiten

Dienstag, 8. April 2014

Dynamic WADL with CDI

The WADL (Web Application Definition Language) is used to describe HTTP-based applications which means that JAXRS applications can and are described by that. Typically it is generated (static or dynamic) with the jersey maven plugin (detailed informations can be found here). But for some reason i could not use either maven nor the jersey plugin. So i had to do it on my own and used it as a little finger exercise. The main goal was to achieve dynamic wadl generation for a JAXRS application. The working steps were relativly easy:
  • Create a JAXB-Model from the current WADL-Specification
  • Create a CDI-Based design for JAXRS resources
In the end you only have to provide a producer class which creates a @Wadl Class[] and inject an instance of @Wadl  @WadlApplication.

@Path("/")
public class MyResource
{
 @Inject
 @Wadl
 @WadlApplication
 Instance<Application> applicationInstance;

 @GET
 @Produces(MediaType.APPLICATION_XML)
 public Application getRoot(@Context UriInfo uriInfo)
 {
  return getWadl(uriInfo);
 }
}

 As a simple example assume that you have a TinkerForge MasterBrick connected to a RaspberryPi. Addionally you want to provide a JAXRS-Resource for every connected sensor. With the sample code below you are now able to extend the WADL dynmically.

public class WadlClassProducer
{
 @Inject
 @SensorAnno
 @Any
 Instance<SensorResource> sensorInstances;

 @Produces
 @Wadl
 public Class[] create()
 {
  List<Class<?>> clazzList = new ArrayList<Class<?>>();
  for (SensorResource sensor : sensorInstances)
  {
   clazzList.add(sensor.getResourceClass());
  }
  return clazzList.toArray(new Class[0]);
 }
}

The sources can be found here.