- Upgrade to jsonschema2pojo 0.4.0
- Fixed bugs where generation would fail due to duplicated class names caused by similar resource names
- Upgrade Jersey 2-ALPHA deps to 2.5.1 some small changes in the APIs
- Fix for XSL for correct return on onClick hander, allows better integration with IDE's
- Interface of MethodNode.getSupportedOutput to support latest WADL model
- Method parameter were not being shown consistently up the tree when using the XSLT
- Reserved words were not being escaped when generating the client
- Non-standard lines in the XSL causing failure on other non oracle transformers
- WADL XSL now generates expandable / collapsable sections
Thursday, February 6, 2014
wadl2java 1.6 released
Friday, May 24, 2013
wadl 1.1.5 released
Thursday, April 25, 2013
Building a simple java client for forecast.io
Unfortunately there was only a textual description of service, nothing I could consume with the Java client tools I have been working with. But I though it would be an interesting experiment to try to document an existing service from scratch.
The first thing I did was to get an example of the data that the service would respond with and run it through a JSON->JSON Schema tool. I used JSONSchema.net which gave me a rough v3 JSON Schema; but it wasn't able to take into account elements that are reused. A little bit of hand editing later I ended up with three JSON Schema files, one for the forecast itself and one for a list of weather details and and one for each particular data point.
From there is was pretty simple to read the developer documentation and write up a simple WADL to describe the two resources provided by the service. Luckily Jason LaPort from the DarkSkys was on hand to fix a few mistake and generally verify my description.
Once I had this all in place I of course found a couple of bugs in my own code, so it was time to update and fix wadl.java.net and release a 1.1.5 version with a revised depdency on the jsonschema2pojo project. This is why a little bit of adhoc expert testing pay dividends.
So taking the WADL from github it is possible to generate a nice clean Java API using the wadl.java.net generator. I won't reproduce the steps to generate the client here, but this is the end result and the kind of code you can get out of it.
// Create a Jersey client and setup for POJO JSON mapping
ClientConfig cc = new DefaultClientConfig();
cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
Client c = Client.create(cc);
// Get current weather for location and check for any alerts
Forecast f = ApiForecastIo_Forecast
.apikey(c, "xxxxxxx") // Get own key from developer.forecast.io
.latitudeLongitude(51.32d, -1.244d) // Some location near where I live
.getAsForecast(
null, // Not JSONP
Units.SI, // Return values in SI units
"hourly,minutely,daily,flags"); // Just return current weather and any alerts
// Output a summary
System.out.println(
f.getCurrently().getSummary() + " " +
f.getCurrently().getTemperature() + " C");
// Output any alerts
List<Alert> alerts = f.getAlerts();
for (Alert altert : alerts) {
System.out.println(
altert.getTitle() + " " + altert.getUri());
}
The nice thing here was just how pleasantly easy describing a service that already exists was, yes I could have written it by hand in Java; but then when I wanted to move to Jersey 2.x I would have to re-write by hand rather that just regenerating from the metadata to a new technology target. (Also did the same for a BBC REST Schedule API, that is in the same git project)
Monday, November 19, 2012
JSON-Schema generation in Jersey
If you are using Maven this should be quite straight forward to update your dependencies assuming you already have jersey and jersey-json. You are just going to need to add a dependency on the "jersey-wadl-json-schema" artefact from the "com.sun.jersey.contribs" group to get the new feature.
If you are outside of Maven the easiest thing to do would be to download the latest jersey-archive and then the jersey-wadl-json-schema jar. How you deploy these is tool specific, but if you are using WLS then here are some specific notes on how to upgrade the version of Jersey.
Once you have this working, you need to create a WadlGeneratorConfig class in order to enable this new grammar generation:
package jersey;
import com.sun.jersey.api.wadl.config.WadlGeneratorConfig;
import com.sun.jersey.api.wadl.config.WadlGeneratorDescription;
import com.sun.jersey.wadl.generators.json.WadlGeneratorJSONGrammarGenerator;
import java.util.List;
public class JsonGeneratorConfig extends WadlGeneratorConfig {
@Override
public List configure() {
return generator(WadlGeneratorJSONGrammarGenerator.class).descriptions();
}
}
This can then be registered in a variety of ways, here is an example using a servlet init param. Note also that to make this example simple that we are using the Jersey POJO mapping; but whilst writing this blog I noticed that this setting affected the format of the JSON version of the WADL in case you try this.
<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.WadlGeneratorConfig</param-name>
<param-value>jersey.JsonGeneratorConfig</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
</web-app>
So I put together a really simple echo service, just to check this is all working:
package jersey;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/echo")
public class EchoResource {
@GET
@Produces("application/json")
public EchoBean echo() {
EchoBean bean = new EchoBean();
bean.setMessage("Hello");
return bean;
}
@POST
@Consumes("application/json")
@Produces("application/json")
public EchoBean echo(EchoBean echo) {
return echo;
}
}
and
package jersey;
public class EchoBean {
public EchoBean() {
super();
}
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
This very simple example results in the following WADL with the JSON-Schema elements referenced:
<?xml version = '1.0' encoding = 'UTF-8'?>
<ns0:application xmlns:ns0="http://wadl.dev.java.net/2009/02">
<ns0:doc xmlns:ns1="http://jersey.java.net/" ns1:generatedBy="Jersey: 1.16-SNAPSHOT 11/19/2012 12:59 AM"/>
<ns0:grammars/>
<ns0:resources base="http://localhost:7103/Jersey/resources/">
<ns0:resource path="/echo">
<ns0:method id="echo" name="GET">
<ns0:response>
<ns0:representation mediaType="application/json" xmlns:ns2="http://wadl.dev.java.net/2009/02/json-schema" ns2:describedby="application.wadl/echoBean"/>
</ns0:response>
</ns0:method>
<ns0:method id="echo" name="POST">
<ns0:request>
<ns0:representation mediaType="application/json" xmlns:ns3="http://wadl.dev.java.net/2009/02/json-schema" ns3:describedby="application.wadl/echoBean"/>
</ns0:request>
<ns0:response>
<ns0:representation mediaType="application/json" xmlns:ns4="http://wadl.dev.java.net/2009/02/json-schema" ns4:describedby="application.wadl/echoBean"/>
</ns0:response>
</ns0:method>
</ns0:resource>
</ns0:resources>
</ns0:application>
The URI application.wadl/echoBean contains this simple JSON-Schema definition:
{
"type" : "object",
"properties" : {
"message" : {
"type" : "string"
}
},
"name" : "echoBean"
}
Now there are a number of limitations in the current design, not least that the generated schema doesn't take into account any notation settings. But I thought this would be enough to provoke feedback on whether this feature would be useful generally. There appears to be a growing interest in JSON-Schema both around the net and internally to Oracle, so it would be interesting to see whether this description becomes more common.
Friday, November 16, 2012
JSON-Schema in WADL
So I began to look at how one would go about attaching a JSON-Schema grammar of a JSON document in a WADL description of a service. This isn't a specification yet; but a proposal of how it might work consistently.
Now I work with Jersey mostly, so lets consider what Jersey will current generate for a service that returns both XML and JSON. So the service here is implemented using the JAX-B binding so they both use a similar structure as defined by the XML-Schema reference by the include.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.16-SNAPSHOT 10/26/2012 09:28 AM"/>
<grammars>
<include href="xsd0.xsd">
<doc title="Generated" xml:lang="en"/>
</include>
</grammars>
<resources base="http://localhost/">
<resource path="/root">
<method id="hello" name="PUT">
<request>
<representation xmlns:m="urn:message" element="m:requestMessage" mediaType="application/json" />
<representation xmlns:m="urn:message" element="m:requestMessage" mediaType="application/xml" />
</request>
<response>
<representation xmlns:m="urn:message" element="m:responseMessage" mediaType="application/json"/>
<representation xmlns:m="urn:message" element="m:responseMessage" mediaType="application/xml" />
</response>
</method>
</resource>
</resources>
</application>
So the first thing we considered was re-using the existing element property, which is defined as a QName, on the representation element to reference an imported JSON-Schema. It is shown here both with and another an arbitrary namespace to it can be told apart from XML elements without a namespace.
<grammars>
<include href="xsd0.xsd" />
<include href="application.wadl/responseMessage" />
</grammars>
<representation element="responseMessage" mediaType="application/json"/>
Or
xmlns:json="http://wadl.dev.java.net/2009/02/json"
<representation
element="json:responseMessage" mediaType="application/json" />
The problem is that the JSON-Schema specification as it stands doesn't have a concept of a "name" property, so each JSON-Schema is uniquely identified by it's URI. Also from my read of the specification each JSON-Schema contains the definition for at most one document - not the multiple types / documents that can be contained in XML-Schema.
So the next best suggestion would be to just use the "filename" part of the URI as a proxy for the URI; but of course that won't necessarily be unique. I could see for example the US government and Yahoo both publishing there own "address" micro format.
The better solution to this problem is to introduce a new attribute, luckily the WADL spec was designed with this in mind, that is of type URI that can be used to directly reference the JSON-Schema definitions. So rather than the direct import in the previous example we have a URI property on the element itself. The "describedby" attribute name comes from the JSON-Schema proposal and is consistent with the rel used on atom links in the spec.
xmlns:json="http://wadl.dev.java.net/2009/02/json-schema"
xmlns:m="urn:message"
<grammars>
<include href="xsd0.xsd" />
</grammars>
<representation
mediaType="application/json"
element="m:responseMessage"
json:describedby="application.wadl/responseMessage" />
The has the secondary advantage in that this format is backwardly compatible with tooling that was relying on the XML-Schema grammar. Although this is probably only of interesting to people who work in tooling / testing tools like myself.
Once you have the JSON-Schema definition then some users are going to want to do away with the XML all together, so finally here is a simple mapping of the WADL to a JSON document that contains just the JSON-Schema information. It has been suggested by Sergey Breyozkin the JSON mapping would only show the json grammars and I am coming around to that way of thinking. I would be interested to hear of a usecase for the JSON mapping that would want access to the XML Schema.
{
"doc":{
"@generatedBy":"Jersey: 1.16-SNAPSHOT 10/26/2012 09:28 AM"
},
"resources":{
"@base":"http://localhost/",
"resource":{
"@path":"/root",
"method":{
"@id":"hello",
"@name":"PUT",
"request":{
"representation":[
{
"@mediaType":"application/json",
"@describedby":"application.wadl/requestMessage"
}
]
},
"response":{
"representation":[
{
"@mediaType":"application/json",
"@describedby":"application.wadl/responseMessage"
}
]
}
}
}
}
}
I am currently using the mime type of "application/vnd.sun.wadl+json" for this mapping to be consistent with the default WADL mime type. I suspect we would want to change this in the future; but it will do for starters.
So this is all very interesting but you can't play with it unless you have an example implementation. I have something working for both the server side and for a Java client generator in Jersey and wadl2java respectively and that will be the topic of my next post. I have been working with Pavel Bucek on the Jersey team on these implementations and the WADL proposal, thanks very much to him for putting up with me.
Thursday, October 4, 2012
wadl2java 1.1.3 released
This generated code is nearly identical to the Jersey 1.x interface so most simple code should compile straight after a swap without too many problems. If the client is making use of ClientResponse these references will have to be replaced with Response; but otherwise the interface will be consistent. I would welcome suggestions as to how I could improve what is generated.
So here is a list of items of changes in the release:
- WADL-25, a patch to allow the passing in of argument to xjc, as provided by Brian Chapman thanks for that..
- There is a problem in when there was not response content type, this type of method now returns the relevant Response object.
- Classes that are @XmlType were being wrapped incorrectly with JAXBElement and the information was being taken from the return class.
- The Proxy objects are now immutable, modifying any property created a new instance.
- There is a now a programmatic interface to override the base URI at each level. (Suggested by Luigi Tagliamonte)
- Fix for Oracle Bug 13804542, generation would fail if inner and outer class names match
- JAX-RS 2.0 generation support available in all tool modes
- Fix for Oracle Bug 14534583, where a fault element was being incorrectly upgraded from a '2006 WADL. This was causing problems with the examples SOAPUI were providing.
- Fix for Oracle Bug 1462282, where the generated exception classes were not actually used in the generated code. All exceptions now extend WebAppilcationException to make migration from 1.x to 2.x easier.
- Improved method generation, removed "application" from media types, removed duplication when method takes and returns the same type (putApplicationXmlAsApplicationXml -> putXml), moved "As" to correct location when we have a type, removed excessive method combinations where we have symmetrical media types. (eg xml,json->xml,json)
- Initial work looking at how to support JSON-Schema type generation, non functional
- Adding functional testing for generated clients as was previously only examining the generated classes. Now they are run for both 1.x and 2.x type clients.
Friday, March 16, 2012
Catalog support for WADL client generation
I have just been fixing a few bugs in the WADL client generator that I have been working on recently. In particular one bug relates to being able to control the server the client uses at deploy time. (WADL-44)
So for example you have a standard packaged ?ar file that contains a client to a production service, in order to run automated testing you want to be able to use the same archive; but redirect the request to an internal server. Using a deployment plan, for example, you can update or introduce an extra deployment descriptor called META-INF/jax-rs-catalog.xml.
Only the base URI for each root resource in the WADL is updated; but this should be enough for most cases. (Would be interested to hear where people though this was limiting). This simple example redirects the client from a production service to a qa server.
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://production.example.com/resource"
uri="http://qa.example.com/resource"/>
</catalog>
If you want to play with this you are going to have to check out the tip of the WADL client project for the moment; but in the coming weeks it will be part of the 1.1.2 release. Feedback always welcome.
Wednesday, October 19, 2011
A little script to update job descriptions on Matrix jobs
We have started to use Matrix jobs in Hudson to try and reduce the amount of clutter on the front page; but we have run into problems in that the job description plugin we used to add the LABEL name to the job id only works for the subordinate tasks. This leaves the top level job without a description.
There are of course other ways you can do this; but since I was playing with the new REST api yesterday, I am going to use this. You could of course use the old RESTy API or indeed the command line tool to perform similar feats. This week I mostly just have a hammer.
Before you use the proxy classes you need to first create a client with the right security credentials configured:
public static Client createClient() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("xxxxx@oracle.com","xxxxxxx"));
return client;
}
The first part of the job is going to be to create proxies for both the parent project and of the child variant:
public static void main(String[] args) {
if (args.length!=2) {
System.err.println("Expecting two parameters project and variant");
}
String project = args[0];
String variant = project + "%2F" + args[1];
System.out.printf("Will copy missing description from %s to %s\n", variant, project);
// Create a Jersey client
Client client = createClient();
// Create a suitable proxy using the client we configured
Projects hudsonProjects = projects(client);
// Handles to the right resources
Projects.ProjectNameBuilds projectBuilds = hudsonProjects.projectNameBuilds(project);
Projects.ProjectNameBuilds variantBuilds = hudsonProjects.projectNameBuilds(variant);
Then we can make a quick map of the variant build number to descriptions by getting the first build object:
// Copy the descriptions out from the variant
Map<Integer, String> variantToDescription = new HashMap<Integer,String>();
BuildsDTO variantBuildsDTO = variantBuilds.getAsApplicationXml(BuildsDTO.class);
for (BuildDTO build : variantBuildsDTO.getBuild()) {
if (build.getDescription()!=null)
{
variantToDescription.put(
build.getNumber(),
build.getDescription());
}
}
Now it turns out that the current version of the API doesn't allow you to update build descriptions; but we can easily read them using this API and then update them using a simple form POST using the same client.
// Update the main project descriptions
BuildsDTO projectBuildsDTO = projectBuilds.getAsApplicationXml(BuildsDTO.class);
for (BuildDTO build : projectBuildsDTO.getBuild()) {
String description = build.getDescription();
// Update description if it has not already been set
if (description == null || description.length()==0) {
String variantDesc = variantToDescription.get(build.getNumber());
if (variantDesc!=null && variantDesc.length()!=0) {
// We need to set the description; but nothing in the REST API
// so we can use the url property to perform a form submit that will
// update the description for us.
MultivaluedMap map = new Form();
map.add("description", variantDesc);
map.add("Submit", "Submit");
WebResource buildResource = client.resource(
build.getUrl() + "submitDescription");
ClientResponse response = buildResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, map);
System.out.printf("Updating build %d with description %s gave response %d\n",
build.getNumber(), variantDesc, response.getStatus());
}
}
}
Monday, October 17, 2011
Getting hold of the schemas for the Hudson REST API, and generating a client
I have been playing with the newish REST-like interface in Hudson 2.1.2 and I wanted to generate a client; but as it only uses Jersey 1.5 so it doesn't contain my fix to publish and connect them up directly. Luckily you can just down load these files from the github repository. You ideally want to add these to the wadl description of the service so download the root WADL using a tool such as wget from http://hudson.my.com/rest/application.wadl and then you can add the required imports.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/" jersey:generatedBy="Jersey: 1.5 01/14/2011 12:36 PM"/>
<grammars>
<include href="build.xsd" />
<include href="common.xsd" />
<include href="fault.xsd" />
<include href="project.xsd" />
</grammars>
<resources base="http://hudson/rest/">
....
Now you can either use the schemas as is and make sure you have annox on your class path when you generate the model classes, or you can find and replace jaxb:extensionBindingPrefixes="xjc annox" with jaxb:extensionBindingPrefixes="xjc".
This will give you a wadl that will generate the interface and the model classes in the same step; we will have to wait for later version of Hudson to connect the types up to the methods. For the moment though if you have a quick look at the WADL it is relatively obvious which types are for which.
/**
*
*/
@Generated(value =
{ "wadl|file:/tmp/workspaceWorkDir5662539174912846886.abbot/Hudson/Hudson-WADL/src/wadl/application.wadl",
"run|ca8e07f8-00d8-40ab-bde3-b15cee244091" }, comments = "wadl2java, http://wadl.java.net",
date = "2011-10-17T14:31:17.818+01:00")
public class Hudson_Rest {
public static void main(String[] args) {
// Write out all projects status
Hudson_Rest.Projects hudsonProjects = projects();
ProjectsDTO projects = hudsonProjects.getAsApplicationXml(ProjectsDTO.class);
for (ProjectDTO project : projects.getProject()) {
System.out.printf("++++ %s +++++\n", project.getName());
System.out.println(project.getHealth().getDescription());
}
// Query the enablement of one particular project
Hudson_Rest.Projects.ProjectName hudsonAbbotSf = hudsonProjects.projectName("abbot_SF");
ProjectDTO abbot_SF = hudsonAbbotSf.getAsApplicationJson(ProjectDTO.class);
System.out.println("Abbot_SF is enabled " + abbot_SF.isEnabled());
}
...
}
So this is a simple read operation, I will look at writing back through this API which will involve configuring the client for authentication in a later installment.
Wednesday, September 7, 2011
Improvements in the WADL client generator
I have recently been working on bringing the useful WADL client generator as originally penned by Marc Hadley more in line with currently technology. I have updated it so that it now uses the Jersey client and also I have made a few modifications to make it easier to use. There is plenty of documentation on the WADL site on how to run the tool in various configurations, but I thought it worth while just to show a simple example of what you might expect.
You can download a snapshot of version 1.1 from here, and hopefully soon a final version of 1.1 will be avaliable here if I have guessed the URL correctly. If you pick the version after the 6th of September it should contain all the bits your need.
So as an example we have a really simple hello world service that has a path param to select the correct languauge, the WADL and the Schema generated in Jersey 1.9 are as follows:
<!-- application.wadl -->
<?xml version = '1.0' encoding = 'UTF-8' standalone = 'yes'?>
<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.9 09/02/2011 11:17 AM"/>
<grammars>
<include href="application.wadl/xsd0.xsd">
<doc title="Generated" xml:lang="en"/>
</include>
</grammars>
<resources base="http://localhost:7101/cr/jersey/">
<resource path="webservice">
<resource path="{lang}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="lang" style="template" type="xs:string"/>
<resource path="greeting">
<method id="hello" name="GET">
<response>
<representation xmlns:ns2="http://example.com/hello" element="ns2:bean" mediaType="*/*"/>
</response>
</method>
</resource>
</resource>
</resource>
</resources>
</application>
<!-- application.wadl/xsd0.xsd -->
<?xml version = '1.0' standalone = 'yes'?>
<xs:schema version="1.0" targetNamespace="http://example.com/hello" xmlns:tns="http://example.com/hello" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bean" type="tns:bean"/>
<xs:complexType name="bean">
<xs:sequence>
<xs:element name="message" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Running this through the wadl tool you end up with a java class that look like this along with the relevant JAX-B classes for the schema type Bean.
package client;
import java.util.HashMap;
import javax.annotation.Generated;
import javax.ws.rs.core.UriBuilder;
import com.example.hello.Bean;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
/**
*
*/
@Generated(value = { "wadl|http://localhost:7101/cr/jersey/application.wadl" },
comments = "wadl2java, http://wadl.java.net", date = "2011-09-07T11:53:39.206+01:00")
public class Localhost_CrJersey {
public static Localhost_CrJersey.Webservice webservice(Client client) {
return new Localhost_CrJersey.Webservice(client);
}
public static Localhost_CrJersey.Webservice webservice() {
return webservice(Client.create());
}
public static class Webservice {
private Client _client;
private UriBuilder _uriBuilder;
private HashMap<String, Object> _templateAndMatrixParameterValues;
/**
* Create new instance using existing Client instance
*
*/
public Webservice(Client client) {
_client = client;
_uriBuilder = UriBuilder.fromPath("http://localhost:7101/cr/jersey/");
_uriBuilder = _uriBuilder.path("webservice");
_templateAndMatrixParameterValues = new HashMap<String, Object>();
}
/**
* Create new instance
*
*/
public Webservice() {
this(Client.create());
}
public Localhost_CrJersey.Webservice.Lang lang(String lang) {
return new Localhost_CrJersey.Webservice.Lang(_client, lang);
}
public static class Lang {
private Client _client;
private UriBuilder _uriBuilder;
private HashMap<String, Object> _templateAndMatrixParameterValues;
/**
* Create new instance using existing Client instance
*
*/
public Lang(Client client, String lang) {
_client = client;
_uriBuilder = UriBuilder.fromPath("http://localhost:7101/cr/jersey/");
_uriBuilder = _uriBuilder.path("webservice");
_uriBuilder = _uriBuilder.path("{lang}");
_templateAndMatrixParameterValues = new HashMap<String, Object>();
_templateAndMatrixParameterValues.put("lang", lang);
}
/**
* Create new instance
*
*/
public Lang(String lang) {
this(Client.create(), lang);
}
/**
* Get lang
*
*/
public String getLang() {
return ((String)_templateAndMatrixParameterValues.get("lang"));
}
/**
* Set lang
*
*/
public Localhost_CrJersey.Webservice.Lang setLang(String lang) {
_templateAndMatrixParameterValues.put("lang", lang);
return this;
}
public Localhost_CrJersey.Webservice.Lang.Greeting greeting() {
return new Localhost_CrJersey.Webservice.Lang.Greeting(_client,
((String)_templateAndMatrixParameterValues.get("lang")));
}
public static class Greeting {
private Client _client;
private UriBuilder _uriBuilder;
private HashMap<String, Object> _templateAndMatrixParameterValues;
/**
* Create new instance using existing Client instance
*
*/
public Greeting(Client client, String lang) {
_client = client;
_uriBuilder = UriBuilder.fromPath("http://localhost:7101/cr/jersey/");
_uriBuilder = _uriBuilder.path("webservice");
_uriBuilder = _uriBuilder.path("{lang}");
_uriBuilder = _uriBuilder.path("greeting");
_templateAndMatrixParameterValues = new HashMap<String, Object>();
_templateAndMatrixParameterValues.put("lang", lang);
}
/**
* Create new instance
*
*/
public Greeting(String lang) {
this(Client.create(), lang);
}
/**
* Get lang
*
*/
public String getLang() {
return ((String)_templateAndMatrixParameterValues.get("lang"));
}
/**
* Set lang
*
*/
public Localhost_CrJersey.Webservice.Lang.Greeting setLang(String lang) {
_templateAndMatrixParameterValues.put("lang", lang);
return this;
}
public Bean getAsBean() {
UriBuilder localUriBuilder = _uriBuilder.clone();
WebResource resource =
_client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
WebResource.Builder resourceBuilder = resource.getRequestBuilder();
resourceBuilder = resourceBuilder.accept("*/*");
return resourceBuilder.method("GET", Bean.class);
}
public <T> T getAs(GenericType<T> returnType) {
UriBuilder localUriBuilder = _uriBuilder.clone();
WebResource resource =
_client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
WebResource.Builder resourceBuilder = resource.getRequestBuilder();
resourceBuilder = resourceBuilder.accept("*/*");
return resourceBuilder.method("GET", returnType);
}
public <T> T getAs(Class<T> returnType) {
UriBuilder localUriBuilder = _uriBuilder.clone();
WebResource resource =
_client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
WebResource.Builder resourceBuilder = resource.getRequestBuilder();
resourceBuilder = resourceBuilder.accept("*/*");
return resourceBuilder.method("GET", returnType);
}
}
}
}
}
This looks little bit wordy, but things become a little bit simpler if you just look at the interface that has been generated. For example you can now access each part of the path directly using the accessor methods. In this example we are asking for just the english version of the greeting:
public class Test
{
public static void main(String[] args) {
Bean bean = Localhost_CrJersey.webservice().lang("en").greeting().getAsBean();
System.out.println(bean.getMessage());
}
}
Finally for each method that returns a JAX-B element there are also two that take Class
public class Test
{
public static void main(String[] args) {
ClientResponse response = Localhost_CrJersey.webservice().lang("en").greeting().getAs(ClientResponse.class);
System.out.println(response.getStatus());
}
}
Now this client currently has limitations in that it doesn't know about HATEOAS and you can't control the URL with deployment descriptors; but it is a start that can hopefully evolve into a more generally useful tool. Also I have played with the constructors for Wadl2Java a little bit to make easier to integrate into IDE tooling, it is the work of a couple of afternoons to wrap this up in a wizard and integrate this into your IDE of choice.
