Home > Articles

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"
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:serviceNS="http://localhost:8080/axis/Test.jws"
       xmlns:ns1="java"
       xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
       xmlns="http://schemas.xmlsoap.org/wsdl/">
 <message name="testResponse">
  <part name="testResult" type="ns1:void"/>
 </message>
 <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"/>
 </message>

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.

CAUTION

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;
 2: 
 3: public class LineItemBean
 4: {
 5:  private String _productCode;
 6:  private int _quantity;
 7:  
 8:  public LineItemBean(String productCode, int quantity)
 9:  {
 10:   _productCode = productCode;
 11:   _quantity = quantity;
 12:  }
 13:  
 14:  public LineItemBean()
 15:  {
 16:  }
 17:  
 18:  public String getProductCode()
 19:  {
 20:   return _productCode;
 21:  }
 22:  
 23:  public void setProductCode(String productCode)
 24:  {
 25:   _productCode = productCode;
 26:  }
 27: 
 28:  public int getQuantity()
 29:  {
 30:   return _quantity;
 31:  }
 32:  
 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;
 2: 
 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";
 10:   
 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" 
        classname="webservices.LineItemBean"/>
 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"/>
 <typeMappings>
  <typeMapping type="ns:order"
         xmlns:ns="urn:com-acme-commerce"
         classname="webservices.LineItemBean"
 deserializerFactory="org.apache.axis.encoding.BeanSerializer$BeanSerFactory"
 serializer="org.apache.axis.encoding.BeanSerializer"/>
 </typeMappings>
</service>

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.

<definitions 
    targetNamespace="http://localhost:8080/axis/services/BeanOrderService"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:serviceNS="http://localhost:8080/axis/services/BeanOrderService"
    xmlns:ns1="urn:com-acme-commerce"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns="http://schemas.xmlsoap.org/wsdl/">
 <message name="submitOrderRequest">
  <part name="arg0" type="xsd:string"/>
  <part name="arg1" type="ns1:LineItem"/>
 </message>
 ...

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;
 3: 
 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;
 9: 
 10: import webservices.LineItemBean;
 11: 
 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;
 20: 
 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:   }
 37: 
 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:   }
 50: 
 51:   LineItemBean lineItem = new LineItemBean(productCode, quantity);
 52:   
 53:   QName lineItemAssociatedQName = new QName("urn:com-acme-commerce", 
                      "LineItem");
 54:   
 55:   BeanSerializer serializer = 
          new BeanSerializer(webservices.LineItemBean.class);
 56:   
 57:   client.addSerializer(webservices.LineItemBean.class,
 58:             lineItemAssociatedQName,
 59:             serializer);
 60:      
 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:   }
 70:   
 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020