Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Parameter Types and Type Mapping

So far, the Web Services you have seen have used simple parameters, such as strings and integers. However, in the real world, most systems will need to pass complex types such as arrays, classes, and data structures. During the rest of today, you will look at how such complex types can be mapped between Java and SOAP/WSDL and create an order service that uses these types.

Mapping Between Java and SOAP/WSDL Types

For simple types, SOAP and WSDL use the representations defined in "XML Schema Part 2: Datatypes" that is part of the W3C XML Schema standard. There is a straight mapping for all Java primitive types except for char. There is also a straight mapping for the Java String class.

If you were to define a Web Service with the following (unlikely) method:

public void test(byte byteArg, short shortArg, int intArg, long longArg,
           float floatArg, double doubleArg, char charArg,
           boolean boolArg, String stringArg)

this would map into WSDL as follows:

<definitions targetNamespace="http://localhost:8080/axis/Test.jws"
 <message name="testResponse">
  <part name="testResult" type="ns1:void"/>
 <message name="testRequest">
  <part name="arg0" type="xsd:byte"/>
  <part name="arg1" type="xsd:short"/>
  <part name="arg2" type="xsd:int"/>
  <part name="arg3" type="xsd:long"/>
  <part name="arg4" type="xsd:float"/>
  <part name="arg5" type="xsd:double"/>
  <part name="arg6" type="ns1:char"/>
  <part name="arg7" type="xsd:boolean"/>
  <part name="arg8" type="xsd:string"/>

Notice that all of the arguments except char are mapped to a type using the xsd prefix, which refers to the http://www.w3.org/2001/XMLSchema namespace.

However, when you start to work with arrays and complex Java types, such as your own classes, more effort must be put into the representation of these mappings. Consider what is done by RMI when you pass Java objects between a client and server:

  • RMI uses the Java serialization mechanism to convert the contents of the object into a byte stream that can be sent across the network.

  • Both client and server must have a definition for the type being passed (or must be able to get hold of one).

  • The remote interface definition uses standard Java syntax to indicate where objects are used as parameters or return values.

When using complex Java types as part of a Web Service, you must address the same issues. However, there is the added complication that you must do this in a platform and language-independent way. Therefore, the following is needed to pass complex parameters as part of a Web Service method:

  • Provide a mechanism to marshal and unmarshal the contents of a complex Java type into an XML format that can be used as part of a SOAP message

  • Deliver the marshalling and unmarshalling mechanism on both the client and the server

  • Indicate in the WSDL definition that certain parameters or return values are complex types, and provide a mapping between the complex types and their associated marshalling/unmarshalling code

Consider also the situation where you are provided with WSDL that has been generated from a non-Java Web Service, such as a Web Service implemented using Microsoft .NET components. This may also contain definitions for complex types that must be mapped into Java types to use that Web Service from Java.

Somebody has to do this mapping, and it is not necessarily straightforward. Sometimes it can be done using automated tools, while at other times it may require custom code.

Mapping Complex Types with Serializers

The JAX-RPC specification defines a serialization framework that can be used to map between complex Java types and their XML representations in WSDL and SOAP. You will define serializer and deserializer classes for each complex type that will be called on by the Web Service runtime to perform this conversion. (See Figure 20.10.)

Figure 20.10 The role of serializers and deserializers in a SOAP request.

Serializers fall into three types:

  • A set of standard serializers are provided as part of the Java Web Service framework. These include serializers for arrays and common classes, such as java.util.Date.

  • Given a JavaBean, a generic serializer can use its getters to extract its data when marshalling, and the associated deserializer can use the setters to populate a new instance when unmarshalling.

  • A custom serializer can be written to create an XML representation of any Java class.

Obviously, the creation of a custom serializer is not a trivial task. Therefore, it is best to try to keep to standard classes and JavaBeans.

To see how complex type mapping works, consider how you could improve the SimpleOrderServer seen previously. The submitOrder method took three parameters—customerId, productCode, and quantity. A more realistic service would take a variety of customer information together with a list of line items, each of which would describe a product and the quantity required of that product. The productCode and quantity can form the basis of a simple line item to start improving the order service. The LineItemBean formed from these is shown in Listing 20.18. As you can see, this provides getters and setters for both the product code and the quantity.


It is important that the JavaBean has a no-argument constructor and the full compliment of getters and setters. Failure to provide all of these can lead to exceptions when trying to marshal or unmarshal these types.

Listing 20.18 LineItemBean.java—Encapsulating the Product Information in a JavaBean

 1: package webservices;
 3: public class LineItemBean
 4: {
 5:  private String _productCode;
 6:  private int _quantity;
 8:  public LineItemBean(String productCode, int quantity)
 9:  {
 10:   _productCode = productCode;
 11:   _quantity = quantity;
 12:  }
 14:  public LineItemBean()
 15:  {
 16:  }
 18:  public String getProductCode()
 19:  {
 20:   return _productCode;
 21:  }
 23:  public void setProductCode(String productCode)
 24:  {
 25:   _productCode = productCode;
 26:  }
 28:  public int getQuantity()
 29:  {
 30:   return _quantity;
 31:  }
 33:  public void setQuantity(int quantity)
 34:  {
 35:   _quantity = quantity;
 36:  }
 37: }

The server-side code can then be altered to use this JavaBean, as shown in Listing 20.19.

Listing 20.19 BeanOrderServer.java—Using the LineItemBean

 1: package webservices;
 3: public class BeanOrderServer
 4: {
 5:  public String submitOrder(String customerID, LineItemBean item)
 6:  {
 7:   String receipt = "Thank you, " + customerID + "\n";
 8:   receipt += "You ordered " + item.getQuantity() + " " + 
                    item.getProductCode() + "'s\n";
 9:   receipt += "That will cost you " + (item.getQuantity() * 50) + 
                               " Euros";
 11:   return receipt;
 12:  }
 13: }

Before you can deploy this updated class, you need a way to tell the Axis server how it can unmarshal an instance of a LineItemBean. If you do not do this, an exception will occur when the server attempts to service a call to submitOrder.

Given that the LineItemBean is a JavaBean, the Axis BeanSerializer can be used to marshal and unmarshal its contents. You instruct the Axis server to use this serializer by defining a bean mapping in the deployment descriptor. Listing 20.20 shows an updated form of the order service deployment descriptor containing a bean mapping between lines 5–7. The bean mapping associates an XML qualified name (a tag name and associated namespace) with a particular Java class. On line 9, the tag LineItem from the namespace urn:com-acme-commerce is defined as representing the Java class webservices.LineItemBean.

Listing 20.20 Defining a Bean Serializer for Use with the BeanOrderService

 1: <admin:deploy xmlns:admin="AdminService">
 2: <service name="BeanOrderService" pivot="RPCDispatcher">
 3:  <option name="className" value="webservices.BeanOrderServer"/>
 4:  <option name="methodName" value="submitOrder"/>
 5:  <beanMappings>
 6:  <acme:LineItem xmlns:acme="urn:com-acme-commerce" 
 7:  </beanMappings>
 8: </service>
 9: </admin:deploy>

All name-to-class mappings contained within the <beanMappings> element will be performed by the BeanSerializer. After you have deployed the BeanOrderService, a listing of the deployed Axis services will reveal a full type mapping for the bean, as shown in the following (you may need to restart your Web server for this mapping to show up):

<service pivot="RPCDispatcher" name="BeanOrderService">
 <option name="methodName" value="submitOrder"/>
 <option name="className" value="webservices.BeanOrderServer"/>
  <typeMapping type="ns:order"

You can see that the mapping information provided in the deployment descriptor has been augmented by the class names for the BeanSerializer.

The final link-up is made on the server side by indicating which parameters to the Web Service method should be subject to this mapping. The WSDL generated for the service shows that the second parameter (arg1) is of the type nsl:LineItem. This type associates it with the namespace urn:com-acme.commerce as defined by the bean mapping in the deployment descriptor.

 <message name="submitOrderRequest">
  <part name="arg0" type="xsd:string"/>
  <part name="arg1" type="ns1:LineItem"/>

The mapping is now set up on the server side. You can now call this service, confident that the correct unmarshalling will take place. All that remains is to call the service from a client. The code shown in Listing 20.21 shows a client for the BeanOrderService.

Listing 20.21 A Client for the BeanOrderService

 1: import java.rmi.RemoteException;
 2: import java.net.MalformedURLException;
 4: import org.apache.axis.AxisFault;
 5: import org.apache.axis.client.ServiceClient;
 6: import org.apache.axis.encoding.BeanSerializer;
 7: import org.apache.axis.utils.Options;
 8: import org.apache.axis.utils.QName;
 10: import webservices.LineItemBean;
 12: public class BeanOrderServiceClient
 13: {
 14:  public static void main(String [] args)
 15:  {
 16:   String customerId = "unknown";
 17:   String productCode = "Widget";
 18:   int quantity = 1;
 19:   ServiceClient client = null;
 21:   try
 22:   {
 23:    Options options = new Options(args);
 24:    client = new ServiceClient(options.getURL());
 25:    args = options.getRemainingArgs();
 26:   }
 27:   catch (MalformedURLException ex)
 28:   {
 29:    System.err.println("Option error: " + ex);
 30:    System.exit(2);
 31:   }
 32:   catch (AxisFault ex)
 33:   {
 34:    System.err.println("Option error: " + ex);
 35:    System.exit(2);
 36:   }
 38:   if (args == null || args.length != 3)
 39:   {
 40:     System.out.println("Usage: SimpleOrderClient -l<endpoint>" + 
 41:   "<customerId> <productCode> <quantity>");
 42:     System.exit(1);
 43:   }
 44:   else
 45:   {
 46:     customerId = args[0];
 47:     productCode = args[1];
 48:     quantity = Integer.parseInt(args[2]);
 49:   }
 51:   LineItemBean lineItem = new LineItemBean(productCode, quantity);
 53:   QName lineItemAssociatedQName = new QName("urn:com-acme-commerce", 
 55:   BeanSerializer serializer = 
          new BeanSerializer(webservices.LineItemBean.class);
 57:   client.addSerializer(webservices.LineItemBean.class,
 58:             lineItemAssociatedQName,
 59:             serializer);
 61:   String receipt;
 62:   try {
 63:     receipt = (String)client.invoke("BeanOrderService",
 64:                  "submitOrder",
 65:                  new Object[] { customerId, lineItem });
 66:   } catch (AxisFault fault) {
 67:     receipt = "No receipt";
 68:     System.err.println("Error : " + fault.toString());
 69:   }
 71:   System.out.println(receipt);
 72:  }
 73: }

The main interest begins at line 51 where the LineItemBean is instantiated. Following this (line 53), an org.apache.axis.utils.QName is created containing the XML qualified name that will represent the LineItemBean as it is passed across the network. The value of this QName is the one shown in the WSDL generated from the server, namely the tag name LineItem in the namespace urn:com-acme-commerce.

A BeanSerializer is then created that will actually perform the mapping. This serializer must know which particular type of JavaBean it is supposed to map. Consequently, it is given the class type (webservices.LineItemBean.class) as a constructor parameter.

Scrolling back to line 24, you can see that the client will be using a ServiceClient to invoke the Web Service method. This is initialised with the service URL (http://localhost:8080/axis/services/BeanOrderService). On lines 57–59, the serializer and the QName are passed to the addSerializer method of the ServiceClient, together with the JavaBean type, so that the ServiceClient knows for which type this serializer is intended.

Finally, the Web Service method itself is invoked on lines 63–65, and the LineItem instance is passed as the second parameter. The client-side runtime will then invoke the serializer you have associated with LineItem when that parameter is marshalled into the SOAP message.

Going Further with Complex Type Mapping

The use of a BeanSerializer is just the start as far as the mapping of complex types is concerned. Taking the example of the LineItem further, you would probably pass an array of LineItem objects into the method. Alternatively, you could create an Order class that held a Collection of LineItems and pass an instance of Order into the method. In this case, you get into the issues of nested serialization and passing complex types into the getters and setters. While some of this is still within the bounds of the serializers provided by Axis, this path leads toward custom serialization—whether such serializers are written by hand or automatically generated by more powerful tools. To create your own serializers, you can subclass the org.apache.axis.encoding.Deserializer class, but the creation of custom serializers is beyond the scope of today's work.

Apart from beans, serializers are provided for other standard types, such as Date and Map, as well as for byte arrays and SOAP arrays.

JAX-RPC defines an extensible type-mapping framework similar to that delivered by Axis in that you can associate serializers with particular Java classes. These mappings are again stored in a type-mapping registry on both the client and the server side. Standard serializers are to be provided for String, Date, Calendar, BigInteger, and BigDecimal, as well as arrays and JavaBeans.

Another area in which progress should be made for type mapping between Java and XML is the Java API for XML Data Binding (JAXB). JAXB will provide more powerful facilities to map between complex Java types and XML representations of those types. As JAXB progresses, it should provide a useful mapping layer and source of serializers.

  • + Share This
  • 🔖 Save To Your Account