Generate Client Stubs using WADL for Rest Service(Jersey)

Required Jars:
asm-3.1.jar
jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
jersey-client-1.17.1.jar
jersey-core-1.17.1.jar
jersey-json-1.17.1.jar
jersey-multipart-1.17.1.jar
jersey-server-1.17.1.jar
jersey-servlet-1.17.1.jar
jsr311-api-1.1.1.jar
mimepull-1.6.jar

-------------------------------------------------------------------------------
EmployeeController.java

package com.restjersey.controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("employee")
public class EmployeeController {

@GET
@Path("/getEmployee/{name}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getEmployee(@PathParam("name") final String name) {

return Response.status(200).entity(name).build();
}
}
----------------------------------------------------------------------------
Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTfulWS</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.restjersey.controller</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 REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
---------------------------------------------------------------------------------------
Step 1 : Use below URL to view WADL in browser

http://localhost:8080/RestJerseyExample/rest/application.wadl

Step 2 : Download wadl-dist-1.1.6-bin.zip from Click here

Step 3 : Extract it to folder C:\stubs and set environment variables as below:

CXF_HOME - C:\stubs\wadl-dist-1.1.6
Path - %CXF_HOME%\lib;%CXF_HOME%\bin;

Step 4 : Open CMD and goto C:\stubs\wadl-dist-1.1.6\bin and run wadl2java.bat

Step 5 : Execute command - wadl2java -o C:\stubs -p com.restjersey.client http://localhost:8080/RestJerseyExample/rest/application.wadl which will generate client stub as below :

package com.restjersey.client;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.uri.UriTemplate;

@Generated(value = {
"wadl|http://localhost:8080/RestJerseyExample/rest/application.wadl"
}, comments = "wadl2java, http://wadl.java.net", date = "2017-04-23T19:54:04.669+05:30")
public class Localhost_RestJerseyExampleRest {

/**
* The base URI for the resource represented by this proxy
*
*/
public final static URI BASE_URI;

static {
URI originalURI = URI.create("http://localhost:8080/RestJerseyExample/rest/");
// Look up to see if we have any indirection in the local copy
// of META-INF/java-rs-catalog.xml file, assuming it will be in the
// oasis:name:tc:entity:xmlns:xml:catalog namespace or similar duck type
java.io.InputStream is = Localhost_RestJerseyExampleRest.class.getResourceAsStream("/META-INF/jax-rs-catalog.xml");
if (is!=null) {
try {
// Ignore the namespace in the catalog, can't use wildcard until
// we are sure we have XPath 2.0
String found = javax.xml.xpath.XPathFactory.newInstance().newXPath().evaluate(
"/*[name(.) = 'catalog']/*[name(.) = 'uri' and @name ='" + originalURI +"']/@uri",
new org.xml.sax.InputSource(is));
if (found!=null && found.length()>0) {
originalURI = java.net.URI.create(found);
}

}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
is.close();
} catch (java.io.IOException e) {
}
}
}
BASE_URI = originalURI;
}

public static Localhost_RestJerseyExampleRest.Employee employee(com.sun.jersey.api.client.Client client, URI baseURI) {
return new Localhost_RestJerseyExampleRest.Employee(client, baseURI);
}

/**
* Template method to allow tooling to customize the new Client
*
*/
private static void customizeClientConfiguration(ClientConfig cc) {
}

/**
* Template method to allow tooling to override Client factory
*
*/
private static com.sun.jersey.api.client.Client createClientInstance(ClientConfig cc) {
return com.sun.jersey.api.client.Client.create(cc);
}

/**
* Create a new Client instance
*
*/
public static com.sun.jersey.api.client.Client createClient() {
ClientConfig cc = new DefaultClientConfig();
customizeClientConfiguration(cc);
return createClientInstance(cc);
}

public static Localhost_RestJerseyExampleRest.Employee employee() {
return employee(createClient(), BASE_URI);
}

public static Localhost_RestJerseyExampleRest.Employee employee(com.sun.jersey.api.client.Client client) {
return employee(client, BASE_URI);
}

public static class Employee {

private com.sun.jersey.api.client.Client _client;
private UriBuilder _uriBuilder;
private Map _templateAndMatrixParameterValues;

private Employee(com.sun.jersey.api.client.Client client, UriBuilder uriBuilder, Map map) {
_client = client;
_uriBuilder = uriBuilder.clone();
_templateAndMatrixParameterValues = map;
}

/**
* Create new instance using existing Client instance, and a base URI and any parameters
*
*/
public Employee(com.sun.jersey.api.client.Client client, URI baseUri) {
_client = client;
_uriBuilder = UriBuilder.fromUri(baseUri);
_uriBuilder = _uriBuilder.path("employee");
_templateAndMatrixParameterValues = new HashMap();
}

public Localhost_RestJerseyExampleRest.Employee.GetEmployeeName getEmployeeName(String name) {
return new Localhost_RestJerseyExampleRest.Employee.GetEmployeeName(_client,
_uriBuilder.buildFromMap(_templateAndMatrixParameterValues), name);
}
public static class GetEmployeeName {

private com.sun.jersey.api.client.Client _client;
private UriBuilder _uriBuilder;
private Map _templateAndMatrixParameterValues;

private GetEmployeeName(com.sun.jersey.api.client.Client client, UriBuilder uriBuilder, Map map) {
_client = client;
_uriBuilder = uriBuilder.clone();
_templateAndMatrixParameterValues = map;
}

/**
* Create new instance using existing Client instance, and a base URI and any parameters
*
*/
public GetEmployeeName(com.sun.jersey.api.client.Client client, URI baseUri, String name) {
_client = client;
_uriBuilder = UriBuilder.fromUri(baseUri);
_uriBuilder = _uriBuilder.path("/getEmployee/{name}");
_templateAndMatrixParameterValues = new HashMap();
_templateAndMatrixParameterValues.put("name", name);
}

/**
* Create new instance using existing Client instance, and the URI from which the parameters will be extracted
*
*/
public GetEmployeeName(com.sun.jersey.api.client.Client client, URI uri) {
_client = client;
StringBuilder template = new StringBuilder(BASE_URI.toString());
if (template.charAt((template.length()- 1))!= '/') {
template.append("/employee/getEmployee/{name}");
} else {
template.append("employee/getEmployee/{name}");
}
_uriBuilder = UriBuilder.fromPath(template.toString());
_templateAndMatrixParameterValues = new HashMap();
UriTemplate uriTemplate = new UriTemplate(template.toString());
HashMap parameters = new HashMap();
uriTemplate.match(uri.toString(), parameters);
_templateAndMatrixParameterValues.putAll(parameters);
}

/**
* Get name
*
*/
public String getName() {
return ((String) _templateAndMatrixParameterValues.get("name"));
}
/**
* Duplicate state and set name
*
*/
public Localhost_RestJerseyExampleRest.Employee.GetEmployeeName setName(String name) {
Map copyMap;
copyMap = new HashMap(_templateAndMatrixParameterValues);
UriBuilder copyUriBuilder = _uriBuilder.clone();
copyMap.put("name", name);
return new Localhost_RestJerseyExampleRest.Employee.GetEmployeeName(_client, copyUriBuilder, copyMap);
}

publicT getAsJson(GenericType returnType) {
UriBuilder localUriBuilder = _uriBuilder.clone();
com.sun.jersey.api.client.WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
resourceBuilder = resourceBuilder.accept("application/json");
com.sun.jersey.api.client.ClientResponse response;
response = resourceBuilder.method("GET", com.sun.jersey.api.client.ClientResponse.class);
if (response.getStatus()>= 400) {
throw new Localhost_RestJerseyExampleRest.WebApplicationExceptionMessage(Response.status(response.getClientResponseStatus()).build());
}
return response.getEntity(returnType);
}

publicT getAsJson(Class returnType) {
UriBuilder localUriBuilder = _uriBuilder.clone();
com.sun.jersey.api.client.WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
resourceBuilder = resourceBuilder.accept("application/json");
com.sun.jersey.api.client.ClientResponse response;
response = resourceBuilder.method("GET", com.sun.jersey.api.client.ClientResponse.class);
if (!com.sun.jersey.api.client.ClientResponse.class.isAssignableFrom(returnType)) {
if (response.getStatus()>= 400) {
throw new Localhost_RestJerseyExampleRest.WebApplicationExceptionMessage(Response.status(response.getClientResponseStatus()).build());
}
}
if (!com.sun.jersey.api.client.ClientResponse.class.isAssignableFrom(returnType)) {
return response.getEntity(returnType);
} else {
return returnType.cast(response);
}
}
}
}


/**
* Workaround for JAX_RS_SPEC-312
*
*/
private static class WebApplicationExceptionMessage
extends WebApplicationException
{


private WebApplicationExceptionMessage(Response response) {
super(response);
}

/**
* Workaround for JAX_RS_SPEC-312
*
*/
public String getMessage() {
Response response = getResponse();
Response.Status status = Response.Status.fromStatusCode(response.getStatus());
if (status!= null) {
return (response.getStatus()+(" "+ status.getReasonPhrase()));
} else {
return Integer.toString(response.getStatus());
}
}

public String toString() {
String s = "javax.ws.rs.WebApplicationException";
String message = getLocalizedMessage();
return (s +(": "+ message));
}

}

}

JerseyClient.java

-------------------------------------------------------------------
package com.restjersey.client;

public class JerseyClient {

public static void main(final String[] args) {
System.out
.println(Localhost_RestJerseyExampleRest.employee().getEmployeeName("Mohsin").getAsJson(String.class));
}
}

Comments

Post a Comment

Popular posts from this blog

Edit/Modify existing PDF using Java(iText)

Verify Digital Signature in PDF using Java(iText) and cacerts

Steps to create SOAP Web service using Eclipse