Enterprise Integration Zone is brought to you in partnership with:

Ryan Heaton is an engineer, architect, and consultant specializing the Web service design and development. Ryan has architected a wide variety of successful Web service applications and frameworks. One of his projects, Enunciate, has been released as a popular open-source Web service development framework. He has performed technical interviews for scores of candidates probing all aspects of Web service design and implementation. Ryan is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. View Full User Profile

A Rich Web Service API for Your Favorite Framework, Part 5: Tapestry

12.21.2008
| 8911 views |
  • submit to reddit

The intent of this how-to series is to demonstrate the development of a rich Web service API on a variety of popular development frameworks. Part 5 (this tutorial) targets Apache Tapestry. (Previous parts: Spring, JBoss Seam, Struts, Wicket.)

We're going to be using Enunciate to supply a rich Web service API to the TimeTracker demo (also hosted here). By the end of the tutorial the TimeTracker application will include the following:

  • REST endpoints. The REST endpoints will supply resources in both XML and JSON data formats.
  • SOAP endpoints. The API will be exposed via SOAP and defined by a well-defined and cosolidated WSDL.
  • Full API Documentation. The Web service API will be fully-documented.
  • Client-side code. The application will provide client-side Java code that will be able to access the Web service API remotely.

Enunciate makes it drop-dead easy to develop this kind of Web service API: a few minor tweaks to the build file and web.xml file, a configuration file, and a pair of service endpoints.

Step 1: Set up the Environment

First make sure you have Maven installed, since that's the build tool we'll be using to run the demo. Then check out the demo from SVN:

svn co http://svn.apache.org/repos/asf/tapestry/tapestry4/tags/4.1.6/tapestry-examples/TimeTracker

The TimeTracker application will be checked out to the TimeTracker directory. From now on, this directory will be referred to as $TIME_TRACKER_HOME. Unfortunately, the application is still pointing to a SNAPSHOT version of Tapestry, so before we move forward, we have to edit the $TIME_TRACKER_HOME/pom.xml file to point to the 4.1.6 (non-snapshot) version of Tapestry:

pom.xml

...
<parent>
<groupId>org.apache.tapestry</groupId>
<artifactId>tapestry-examples</artifactId>
<!--<version>4.1.6-SNAPSHOT</version>-->
<version>4.1.6</version>
</parent>
...

Once this is done, run the application:

mvn jetty:run-exploded

You should be able to open up a browser to http://localhost:8080/app to see the TimeTracker demo in all it's glory.

We next need to integrate Enunciate with our project. We can do this by adding a dependency on Enunciate to our pom.xml file. Also, the service endpoints we're going to be writing need cglib:

pom.xml

...
<dependencies>
<dependency>
<groupId>org.codehaus.enunciate</groupId>
<artifactId>enunciate-rt</artifactId>
<version>1.8.1</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.1_3</version>
</dependency>

...
</dependencies>
...

And we also add the maven-enunciate-plugin to the list of plugins in our pom.xml file:

pom.xml

...
<plugins>
...
<plugin>
<groupId>org.codehaus.enunciate</groupId>
<artifactId>maven-enunciate-plugin</artifactId>
<version>1.8.1</version>
<executions>
<execution>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
...

Now let's add a Web service API.

Step 2: Tweak the Deployment Descriptor

We've got to apply some minor changes to our web.xml file to make room for our Web service API. We first get rid of the section that defines and applies the Tapestry RedirectFilter. That section looks like this, commented out:

web.xml

...
<!--<filter>-->
<!--<filter-name>redirect</filter-name>-->
<!--<filter-class>org.apache.tapestry.RedirectFilter</filter-class>-->
<!--</filter>-->

<!--<filter-mapping>-->
<!--<filter-name>redirect</filter-name>-->
<!--<url-pattern>/</url-pattern>-->
<!--</filter-mapping>-->
...

We now have to apply the HiveMindFilter to the application so that our endpoints can access the components that are configured by Tapestry.

web.xml

...
<filter>
<filter-name>HiveMind Filter</filter-name>
<filter-class>org.apache.hivemind.servlet.HiveMindFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>HiveMind Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...

Finally, the web.xml file has to move from $TIME_TRACKER_HOME/src/context/WEB-INF/web.xml to $TIME_TRACKER_HOME/web.xml. This is so it doesn't overwrite the web.xml file that will eventually be generated by Enunciate.

mv src/context/WEB-INF/web.xml .
info You can download the final web.xml file here

 

Step 3: Enunciate Configuration

Here is an Enunciate configuration file that Enunciate uses to expose the Web service API for the TimeTracker service. Drop that in $TIME_TRACKER_HOME (next to the pom.xml file). Let's briefly go over the basic parts of this file.

The <api-classes> element simply tells Enunciate what classes are to be used to define the Web service API. By default, Enunciate assumes all classes in the project are a part of the Web service API, but the TimeTracker demo has a lot of other classes that are used to drive the UI and that were never meant to define the Web service API, so we have to tell Enunciate that only the classes in the org.apache.tapestry.timetracker.model and org.apache.tapestry.timetracker.ws packages are used to define our Web service API:

...
<api-classes>
<include pattern="org.apache.tapestry.timetracker.model.*"/>
<include pattern="org.apache.tapestry.timetracker.ws.*"/>
</api-classes>
...

The balance of the configuration file is used to define behavior in a specific Enunciate module. Enunciate generates the documentation of our Web service API from the JavaDocs of our API classes. By configuring the docs module, we tell Enunciate to put the documentation in the /api directory of the application and assign the documentation a title.

Enunciate assembles the Web service API in the form of a standard J2EE servlet application, and it needs to be merged with the TimeTracker demo. We do this by merging the Enunciate-generated web.xml file with the TimeTracker web.xml file.

...
<modules>
<docs docsDir="api" title="Time Tracker Example API"/>
<spring-app>
<war mergeWebXML="web.xml"/>
</spring-app>
</modules>
...

 

Step 4: Write the API Endpoints

Let's expose two services: a ProjectService and a TaskService. We'll create a new package, org.apache.tapestry.timetracker.ws where we can put our new service classes, named ProjectService.java and TaskService.java respectively.

For each service, we'll write two methods: a get method that gets a project or task by id, and a list method that lists all the projects or tasks.

SOAP Metadata

To expose a SOAP interface we just need to apply some JAX-WS metadata to our service classes. Actually, all we have to do is apply the @javax.jws.WebService annotation to each class.

REST Metadata

Of course we also want to apply a REST interface to our API. This can be done by applying JAX-RS annotations to our service classes, but it's a bit more complicated because of the additional constraints of a REST API.

First of all, you have to map the service to a URI path by applying the @javax.ws.rs.Path annotation to the service class. We'll mount the ProjectService at the "/projects" path and the TaskService at the "/tasks" path.

Next, since you're limited to a constrained set of operations, you have to annotate specific methods that are to be included in the REST API. You must specify (1) the HTTP method that is used to invoke the method and (2) the subpath that is used to locate it. We'll keep it simple by exposing just the get methods via the HTTP GET operation using the javax.ws.rs.GET annotation and mounting the method at the "/project/{id}" and "/task/{id}" paths, respectively, using the javax.ws.rs.Path annotation. The "{id}" on the path will specify the id of the project/task that we want to get. This means that the method parameter must be annotated with the @javax.ws.rs.PathParam annotation which is also used to specify the name of the path parameter.

Of course, you can expose other methods using other annotations, but we'll refer you to the JAX-RS documentation to learn how to do that.

Here's what our classes look like when we're done:

ProjectService.java

package org.apache.tapestry.timetracker.ws;

import org.apache.tapestry.timetracker.model.Project;
import org.apache.tapestry.timetracker.dao.ProjectDao;
import org.apache.hivemind.Registry;
import org.apache.hivemind.servlet.HiveMindFilter;
import org.codehaus.enunciate.modules.spring_app.HTTPRequestContext;

import javax.jws.WebService;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import java.util.List;

/**
* Service for retrieving and updating projects.
*/
@WebService
@Path ("/projects")
public class ProjectService {

/**
* Get a project by id.
*
* @param id The id of the project.
* @return The project id.
*/
@Path("/project/{id}")
@GET
public Project getProject(@PathParam ("id") long id) {
for (Project project : listProjects()) {
if (project.getId() == id) {
return project;
}
}

return null;
}

/**
* The list of projects.
*
* @return The list of projects.
*/
public List<Project> listProjects() {
ProjectDao dao = (ProjectDao) getRegistry().getService(ProjectDao.class);
return dao.list();
}

private Registry getRegistry() {
return HiveMindFilter.getRegistry(HTTPRequestContext.get().getRequest());
}
}

TaskService.java

package org.apache.tapestry.timetracker.ws;

import org.apache.tapestry.timetracker.model.Task;
import org.apache.tapestry.timetracker.dao.TaskDao;
import org.apache.hivemind.Registry;
import org.apache.hivemind.servlet.HiveMindFilter;
import org.codehaus.enunciate.modules.spring_app.HTTPRequestContext;

import javax.jws.WebService;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import java.util.List;

/**
* Service for retrieving and updating tasks.
*/
@WebService
@Path ("/tasks")
public class TaskService {

/**
* Get a task by id.
*
* @param id The id of the task.
* @return The task id.
*/
@Path("/task/{id}")
@GET
public Task getTask(@PathParam ("id") long id) {
for (Task task : listTasks()) {
if (task.getId() == id) {
return task;
}
}

return null;
}

/**
* The list of tasks.
*
* @return The list of tasks.
*/
public List<Task> listTasks() {
TaskDao dao = (TaskDao) getRegistry().getService(TaskDao.class);
return dao.list();
}

private Registry getRegistry() {
return HiveMindFilter.getRegistry(HTTPRequestContext.get().getRequest());
}
}
info Note the private getRegistry() methods defined on each service. This is what allows us access into Tapestry's component container to get the components (DAOs) that support our services.
info These two classes can also be downloaded here and here.

One final thing is needed before we can deploy our services. The services return instances of org.apache.tapestry.timetracker.model.Project and org.apache.tapestry.timetracker.model.Task, which will be serialized into XML and JSON. In order to do this we need to apply the javax.xml.bind.annotation.XmlRootElement annotation to each of these classes so that JAXB will know how to serialize and deserialize them:

Project.java

@XmlRootElement
public class Project implements Serializable, Persistent
{
...
}

Task.java

@XmlRootElement
public class Task implements Serializable, Persistent
{
...
}

 

Step 4: Build and Deploy

Back on the command-line:

mvn clean jetty:run-exploded

 

Behold the Glory

Your application is fully-functional at http://localhost:8080/app.

Tapestry Home

Check out the documentation for your new Web service API at http://localhost:8080/api/:

Tapestry API Home

Everything is documented, scraped from the JavaDoc comments. Here's the documentation for the SOAP API:

Tapestry SOAP Docs

And documentation for the REST API:

Tapestry REST Docs

And you can download client-side libraries that Enunciate generated and can be used to invoke your Web service API:

Tapestry Client Downloads

What about your WSDL? http://localhost:8080/api/ns0.wsdl

Tapestry WSDL

What about your XML-Schema? http://localhost:8080/api/ns1.xsd

Tapestry Schema

Want to see your API in action? Your SOAP endpoints are mounted at the /soap subcontext, and your REST endpoints are mounted at the /rest subcontext. To view a project, just use the path we defined with JAX-RS annotations relative to the /rest subcontext. So to view the project identified by id "1", we use http://localhost:8080/rest/projects/project/1:

Tapestry XML Example

As a convenience, the same XML resource can also be found at http://localhost:8080/xml/projects/project/1. And if you want to get that same resource as JSON, you can use http://localhost:8080/wicket-examples/json/projects/project/1.

And Beyond...

Well, that's how easy it is to add a Web service API to you Wicket application. But we've only barely scratched the surface of what Enunciate can do. What about any of this:

  • Security (HTTP Auth, OAuth, form-based login, session management, etc.)
  • GWT RPC endpoints and client-side JavaScript for accessing them.
  • AMF endpoints and client-side ActionScript for accessing them.
  • Streaming API for large requests.
  • Etc.

At this point, it's only a matter of configuration....

Published at DZone with permission of Ryan Heaton, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)