Monday, January 14, 2013

REST WADL / Extending WadlGenerator in CXF




A problem in the world of wadl, is that the documentation level on the wadl level is not great.
An example:
<resource path="/agents">
                <method name="GET">
                                <request>
                                                <param name="externalAgentRef" style="query" type="xs:string"/>
                                </request>
                                <response>
                                                <representation mediaType="application/json"/>
                                </response>
                </method>
</resource>

In this example you can see that the default WadlGenerator will display all parameters in the input, but the output is defined as application/json. What we want is for the xml to describe the object that is serialized on the output.
Solution:
To do this we need do define a provider for the jaxrs:
<jaxrs:providers>
<bean class="...WadlGeneratorEx">
<property name="linkJsonToXmlSchema" value="true" />
</bean>                                 
</jaxrs:providers>

CXF does not have a standard interface for the Wadl generator, so you need to extend the current WadlGenerator (http://cxf.apache.org/javadoc/latest/org/apache/cxf/jaxrs/model/wadl/WadlGenerator.html).
Since the class was not created properly for overriding methods, I copied to whole class to a new class with the inheritance of:
public class WadlGeneratorEx extends WadlGenerator implements RequestHandler
On the method: private void handleRepresentation, I added the following line:
sb.append(" classImpl=\"").append(type.getSimpleName()).append("\"");

The new output looks like:
<representation mediaType="application/json" classImpl="Agent"/>

You can now add any other xml attributes you need for documentation.


No comments:

Post a Comment