This article introduces a couple of techniques that you can use to build interoperable Web services that take and return object collections. This is the first of a series of articles covering this subject. Future articles will cover more detailed scenarios. (This intermediate-level article was first published by IBM developerWorks, May 28, 2004, at http://www.ibm.com/developerWorks).
It is quite common for applications to manipulate collections of objects, passing them as arguments to functions and returning them when the processing is complete. There are many ways to represent these collections in most programming languages. They can be expressed as ordered vectors, unordered groups, linked lists, trees, graphs or other forms that the programming language supports. The Java language provides an entire library of collection types in the java.util package. The question, however, is how should you pass collections across a Web services invocation?
Can I use my favorite Java collection type?
To illustrate some issues brought about by the use of standard Java collection classes, let's suppose you want to create a customer service with a getCustomers operation. You might create a JavaBean that returns a collection of Customer objects based on some search criteria. You peruse the collection classes that the Java language offers and decide to use the java.util.LinkedList class. Your CustomerService class might look like the code mock-up in Listing 1:
Listing 1. The CustomerService class using a LinkedList
import java.util.LinkedList;
public class TheCustomerService { public LinkedList getCustomers(String queryString) { Customer customer1, customer2; /* ... retrieve customers for query ... */ LinkedList list = new LinkedList(); /* iterate over the result set assigning to the list */ list.add(customer1); list.add(customer2); return list; } }
The next step is to expose this class as a Web service, and so you choose JAX-RPC-compliant tooling to generate the required artifacts, such as the WSDL file that describes the service interface. This is where the trouble starts. The JAX-RPC specification does not define a mapping for the LinkedList class. Instead, it mentions that each implementation can decide if and how this class is mapped and how instances of the class are serialized to and from XML.
For example, Listing 2, below, shows what the WebSphere Application Server tooling generates as the XML Schema for the class listed in Listing 1: