BUY THIS BOOK
Add to Cart

Print Book $39.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £28.50

What is this?

Looking to Reprint this content?


Java Web Services in a Nutshell
Java Web Services in a Nutshell By Kim Topley
June 2003
Pages: 662

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
This book is an introduction to, and a quick reference for, the Java APIs for web services as implemented in the J2EE 1.4 platform. This chapter begins with a high-level overview of web services, using a real-world example to show why you might need to create one and how it would differ from a traditional HTML-based web application. It then moves on to introduce the technologies that have been developed to enable web services and describes how those technologies have been made available to Java developers. The chapter closes by demonstrating the steps required to build a client application that can communicate with and present information from the web service interface provided by the online bookseller Amazon.com.
In early 2002, Sun Microsystems released the first version of their Java Web Services Developer's Pack (JWSDP). This large download contained everything that a developer needs to begin creating web services using the Java platform. When it appeared, the questions that most developers immediately asked were just exactly what is a web service and why should I be interested in finding out how to build or use one? If, at that time, you looked around the bookstores and the Internet for an answer to these questions, your conclusion would most likely have been that there was plenty of hype, promise, and marketing talk from those companies interested in promoting web services to other companies (and in particular to their Chief Technology Officers), but very little that would be of real use to hands-on developers trying to come to terms with a new technology. Even today, a full year later, it is still difficult to find a consistent definition of what constitutes a web service. The most useful definition that I have been able to find is the following, which appears in the Web Services Architecture document published by the World Wide Web Consortium (W3C), available for download from their web site at http://www.w3.org/TR/ws-arch:
A web service is a software system identified by a URI, whose public interfaces and bindings are defined and described using XML. Its definition can be discovered by other software systems. These systems may then interact with the Web service in a manner prescribed by its definition, using XML-based messages conveyed by Internet protocols.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is a Web Service?
In early 2002, Sun Microsystems released the first version of their Java Web Services Developer's Pack (JWSDP). This large download contained everything that a developer needs to begin creating web services using the Java platform. When it appeared, the questions that most developers immediately asked were just exactly what is a web service and why should I be interested in finding out how to build or use one? If, at that time, you looked around the bookstores and the Internet for an answer to these questions, your conclusion would most likely have been that there was plenty of hype, promise, and marketing talk from those companies interested in promoting web services to other companies (and in particular to their Chief Technology Officers), but very little that would be of real use to hands-on developers trying to come to terms with a new technology. Even today, a full year later, it is still difficult to find a consistent definition of what constitutes a web service. The most useful definition that I have been able to find is the following, which appears in the Web Services Architecture document published by the World Wide Web Consortium (W3C), available for download from their web site at http://www.w3.org/TR/ws-arch:
A web service is a software system identified by a URI, whose public interfaces and bindings are defined and described using XML. Its definition can be discovered by other software systems. These systems may then interact with the Web service in a manner prescribed by its definition, using XML-based messages conveyed by Internet protocols.
In essence, then, a web service is something that provides an interface defined in terms of XML messages and that can be accessed over the Internet (or, of course, an Intranet). What about looking at some real examples of web services to see what they are actually being used for? This is where it gets a little bit harder. At the present time, there aren't many real web services deployed and available on the Internet, although it is expected that this situation will change as web service standards, in particular those related to security, are published and start being implemented over the next year or so.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The SOAP Protocol
The web service definition cited earlier in this chapter stated that a web service communicates using "XML-based messages conveyed by Internet protocols." Although it is expected that there will be a choice of web service protocols in the future, at the present time, web services communicate using Simple Object Access Protocol (SOAP). SOAP is an XML-based protocol that can be carried over any transport mechanism capable of delivering a byte stream. In practice, SOAP messages are usually exchanged between clients and services that are resident in web containers and are typically encapsulated inside an HTTP request or response message. However, nothing in the SOAP 1.1 specification (which can be obtained from the W3C web site at http://www.w3c.org/TR/SOAP) prevents the use of other transport mechanisms, such as FTP, SMTP or even JMS; in fact, both Apache SOAP and its successor, Axis, support the use of SMTP as the carrier for SOAP messages.
A basic SOAP message consists of an envelope that may contain any number of headers plus a body. These parts are delimited by XML elements called Envelope, Header, and Body, which belong to a namespace defined by the SOAP specification. Although the specification defines rules that implementations must follow when creating the structure of a SOAP message, it says nothing about the application-dependent information that the message may contain, apart from the fact that any content conveyed within the envelope must be valid XML. Example 1-1 shows a typical SOAP message.
Example 1-1. A SOAP message
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" 
              xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
              xmlns:enc="http://schemas.xmlsoap.org/soap/encoding/" 
              xmlns:ns0=
                   "urn:jwsnut.chapter6.headerbookservice/types/HeaderBookQuery"
              xmlns:ns1=
                   "urn:jwsnut.chapter6.headerbookservice/wsdl/HeaderBookQuery"
              env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <env:Header>
        <ns1:auth xsi:type="ns0:Authentication">
            <UserName xsi:type="xsd:string">JWSUserName</UserName>
            <Password xsi:type="xsd:string">JWSPassword</Password>
        </ns1:auth>
    </env:Header>
    <env:Body>
        <ns1:getBookAuthor>
            <String_1 xsi:type="xsd:string">Java in a Nutshell</String_1>
            <String_2 xsi:type="xsd:string" xsi:nil="1"/>
        </ns1:getBookAuthor>
    </env:Body>
</env:Envelope>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Describing and Discovering Web Services
One of the clauses in the W3C definition of a web service states that its "definition can be discovered by other software systems." In order to make this possible, the web service standards include:
  • A language used to define the interfaces provided by a web service, in a manner that is not dependent on the platform on which it is running or the programming language used to implement it
  • A provision for a registry within which these definitions can be placed
Since all access to web services uses XML messaging, it is appropriate that the language used to describe a web service should itself be XML-based. The Web Service Description Language (WSDL) was originally defined by Microsoft, IBM, and Ariba, and is now subject to standardization by the W3C consortium. W3C recently published a draft of its official variant of WSDL (Version 1.2), which can be downloaded from its web site at http://www.w3c.org. At the time of this writing, however, most existing WSDL-aware software (including that provided by Sun Microsystems) is based on WSDL Version 1.1.
As you'll see in Chapter 5, WSDL describes a web service by defining the messages that it accepts and the reply messages that it returns. These messages are actually defined first in abstract terms and then bound to one or more message and transport protocols. Today, of course, web services use SOAP as the messaging protocol, and therefore almost all WSDL files will define a binding of the service to SOAP messages delivered over the HTTP protocol. WSDL is not a difficult metalanguage to learn, and it is useful to be able to glance at a WSDL file to get an overview of the interface of a service. However, you don't really need to be able to do much more than this because WSDL definitions are usually both created and consumed by software tools. As you'll see later in this chapter, once you obtain the WSDL definition of a service, the first thing to do is generate a Java interface from it that provides the same operations as the service itself. Not only is a Java interface much easier to understand than the corresponding WSDL, but you can also use the interface when writing your client application, or when creating an implementation of the service itself, if that is your assigned task.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
J2EE Web Service APIs
Java web services are one of the major new features in the J2EE 1.4 platform, which has integrated versions of some of the APIs that Sun Microsystems released as part of the Java Web Services Developer's Pack in 2002. Figure 1-2 shows the various web service APIs (represented by the shaded areas) and how they fit together.
Figure 1-2: The J2EE 1.4 and JWSDP web service APIs
Working up from the bottom of the diagram, by definition, all web services depend on XML, since the messages exchanged between the service provider and the service consumer are encoded in XML. At the present time, these messages are carried using the SOAP protocol, which is itself based on XML. It is generally accepted, however, that SOAP is only the current state of the art and need not be the only web service protocol. Layered above SOAP and XML are the various web service APIs, which are summarized in the following sections:
WSDL
As described earlier, WSDL is an XML vocabulary used to describe the interface provided by a web service. Both J2EE 1.4 and JWSDP support the use of WSDL 1.1 to specify service interfaces, but do not provide an API for application code to directly manipulate WSDL. At the time of this writing, a standard API (called JWSDL) that provides this functionality is under development by the JSR 110 expert group. See http://jcp.org/jsr/detail/110.jsp for details. WSDL is discussed in Chapter 5.
SAAJ
SAAJ (SOAP with Attachments API for Java) provides a direct programming interface to the SOAP protocol. If you are used to low-level protocol handling and don't mind building your own SOAP messages, then you will likely find SAAJ quite simple to use, but for most application developers it is probably not the right place to start. You'll find detailed coverage of the API in Chapter 3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Example Web Service
Although it might appear from Figure 1-1 that there is a lot to learn before you can properly make use of web services, in practice, this is not true. Even though the technology is still relatively new, there are already tools in existence that simplify life for both the end user and the developer. To illustrate this, let's look at how you might go about the task of developing a client application for the web service provided by Amazon.com.
First of all, how would you know that Amazon.com offers a web service? One way to find out is to visit their web site. In general, though, when looking for web services, you won't know in advance all of the companies that might offer the service that you need, so you will most likely go to an electronic business registry and perform a search based on criteria such as industry sector, country of residence, etc. In Chapter 7, you'll see exactly how businesses can publish information to a registry and attach classifications to it so that you can, indeed, perform a search based on various criteria, much as you would when looking for a business in the Yellow Pages.
Figure 1-3 shows the result of performing a search for Amazon.com in a UDDI business registry, which in this case is hosted by IBM. As it happens, Amazon.com has not applied any meaningful criteria to its entry in this registry (at least at the time of writing), so I did not find it by looking for booksellers. However, in an ideal world, this would be possible and, no doubt, for many other businesses, a search using reasonable criteria would produce the desired results. As you can see, the information on this page includes the URL of the WSDL definition of the service.
Figure 1-3: Results of looking for details of the Amazon.com web service in a UDDI registry
The WSDL definition can be downloaded using a web browser and, since it is an XML document, can be inspected to determine the details of the service interface. However, there is a simpler way. Using a tool called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: JAX-RPC
The Java API for XML-based RPC (JAX-RPC) is designed to provide a simple way to create remote procedure call-based web services in which either the client or the server (or both) run on the Java platform without requiring the developer to be aware of the way that the SOAP messages that carry the procedure call request and response are encoded. Because JAX-RPC is based around remote procedure calls, the programming model will be very familiar to Java developers who have used RMI or CORBA.
In order to use the more powerful features of JAX-RPC, you need to have some understanding both of SOAP and of WSDL, an XML-based language that describes the interface to a web service. These topics are covered in Chapter 3 and Chapter 5, respectively. However, you don't need to know anything about either of them in order to become a JAX-RPC programmer. This chapter provides a straightforward introduction to JAX-RPC by demonstrating how to create and deploy a simple JAX-RPC web service and a client application that calls it, using familiar-looking Java code and only a very small amount of XML. The more advanced features of JAX-RPC will be covered in detail in Chapter 6, once the details of SOAP and WSDL are explained.
The JAX-RPC specification was developed under the Java Community Process as JSR 101 and is available for download from http://jcp.org/jsr/detail/101.jsp.
JAX-RPC was designed to provide a simple way for developers to create web services and web service clients using techniques that are not very different from those used in nondistributed Java programming. Programming with JAX-RPC is very similar to using RMI to create a distributed application, in the sense that client code appears to be making ordinary method calls on local objects. In reality, however, the infrastructure handles these calls by converting them to messages that are sent over a network to the server, where they cause a local call to be made on the actual method implementation. The results of this call are used to create a reply message that is sent back the client, where they are extracted and presented as return values from the client application's method call.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JAX-RPC Overview
JAX-RPC was designed to provide a simple way for developers to create web services and web service clients using techniques that are not very different from those used in nondistributed Java programming. Programming with JAX-RPC is very similar to using RMI to create a distributed application, in the sense that client code appears to be making ordinary method calls on local objects. In reality, however, the infrastructure handles these calls by converting them to messages that are sent over a network to the server, where they cause a local call to be made on the actual method implementation. The results of this call are used to create a reply message that is sent back the client, where they are extracted and presented as return values from the client application's method call.
Although there are similarities between RMI and JAX-RPC, the major difference arises from the fact that the messages exchanged between JAX-RPC clients and services are encoded using an XML-based protocol and can potentially be carried by a range of transport-level protocols, including HTTP (or its more secure variant HTTPS), SMTP, or even FTP. JAX-RPC allows a client written in the Java programming language to access a service implemented on, for example, the Microsoft .NET platform, whereas RMI clients and servers must both be written in Java (although it is possible to expose an RMI/CORBA hybrid service written in any language that has a binding to CORBA IIOP). In other words, it can communicate with foreign services without needing to be aware of the technology that its peer is actually using.
One of the benefits of using JAX-RPC over a lower-level web services technology such as SAAJ or JAXM (both of which will be covered later in this book) is that it doesn't require you to know much about XML before you can start building a distributed application. This is because, with a few exceptions that fall into the advanced category, the programming interfaces are completely independent of both the underlying messaging infrastructure and the transport protocol that is used to carry the XML messages. The JAX-RPC specification requires every implementation to support at least the use of SOAP over HTTP 1.1, but, as a developer, you can use JAX-RPC without having to be an expert in XML, SOAP, or HTTP. On the other hand, if these technologies are more than acronyms to you, as you'll see in Chapter 6, it is possible to use some of the more advanced JAX-RPC features to gain access to the lower levels. Here, you can directly handle SOAP headers or extend the set of data types that the client and server can exchange beyond those supported transparently by JAX-RPC.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Programming with JAX-RPC
Now that you've seen a simple example of JAX-RPC programming, this section lifts the hood a little and looks more closely at some of the details that were skimmed over in the first part of this chapter. Although much of what follows is completely generic, it isn't possible to give a complete description of JAX-RPC programming without going beyond the bounds of the specification, since there are certain aspects of the programming model that vendors are permitted to implement in any convenient manner. Where this is the case, we'll make it clear that what is being described is not covered by the specification, and we'll use the JAX-RPC reference implementations in the J2EE 1.4 platform and the JWSDP as typical examples.
Web service development with JAX-RPC begins either with the definition of the service itself as a Java interface or by importing a service definition in the form of a WSDL document. In this chapter, for the sake of simplicity, we consider only the first case and defer discussion of WSDL and of using WSDL as the starting point for JAX-RPC development to Chapter 5 and Chapter 6, respectively. As noted earlier, using Java to define the service endpoint interface is not sufficient if you want to publish the service so that it can be used by clients written in other programming languages. In order to be truly open, the service definition has to be exported as a WSDL document. However, using Java as the definition language is convenient at this stage since we haven't yet described WSDL. Therefore, we will continue to discuss JAX-RPC service definitions and the rules that apply to them in terms of their bindings to the Java language for the rest of this chapter.

Section 2.2.1.1: Interface method definitions

A Java web service endpoint interface must obey the following rules:
  • The interface must extend java.rmi.Remote.
  • Each interface method must declare that it throws
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using EJBs to Implement Web Services
So far, you have seen how to implement a web service and arrange for it to be hosted by a servlet in a web container. J2EE 1.4 extends this model by allowing you to implement web services as stateless session beans in the EJB container or, if you want to view it another way, to advertise the remote interface of an existing stateless session bean as a web service, provided that the interface methods meets the requirements of a JAX-RPC service endpoint interface.
Session beans typically have a combination of the following:
  • A remote interface that contains the service methods that remote clients can invoke. This interface is required to extend javax.ejb.EJBObject.
  • A local interface that contains the methods available to clients that reside with the session bean. This may be the same set of methods as those in the remote interface, but this is not required. The local interface extends javax.ejb.EJBLocalObject.
  • A home interface that remote clients use to manage their view of the lifecycle of the session bean, including obtaining an instance of it and releasing it when it is no longer required. The home interface must extend javax.ejb.EJBHome and is required to exist if the session bean provides a remote interface.
  • A local home interface, which is the equivalent of the home interface for clients that are local to the bean and extends javax.ejb.EJBLocalHome. The local home interface is required only if the bean provides a local interface.
  • An implementation class or classes that provide the bean's code. One of these classes is considered to be the main implementation class of the bean and must implement the javax.ejb.SessionBean interface.
Session beans that host web services must provide and implement a service endpoint interface like the BookQuery interface defined for the book web service described in this chapter. This interface must, of course, satisfy the usual JAX-RPC requirements described in Section 2.1.2.1, earlier in this chapter, and will ultimately be published to clients in the form of a WSDL definition. The session bean may also have remote and/or local interfaces and the corresponding home and local home interfaces. However, a bean that is implemented simply in order to host a web service is not required to be accessible to either local or remote clients as an EJB and therefore is not required to provide the local and remote interfaces (or their home interface counterparts). Thus, although it is possible to extend an existing session bean so that it can be exposed as a web service by defining a service endpoint interface that advertises some or all of its existing business methods, it is not necessary to invent a local or remote interface or home interfaces for a new bean that is only intended to be used as a web service.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: SAAJ
In the last chapter, you saw how to use JAX-RPC to create web services based around the use of remote procedure calls. Even though JAX-RPC uses an XML-based protocol, there was hardly any XML in evidence in Chapter 2. For the most part, JAX-RPC does a very good job of hiding the details of messages that are exchanged between a web service and its client during a remote procedure call. However, most of the more advanced JAX-RPC features require an understanding of SOAP, the XML-based protocol on which JAX-RPC in particular, and web services in general, are based. This chapter paves the way for a more in-depth examination of JAX-RPC by introducing SOAP, together with SAAJ, which is a Java API for creating, sending, and receiving SOAP messages.
SAAJ, which stands for SOAP with Attachments API for Java, provides a convenient API for constructing SOAP messages without having to directly create the XML yourself. SAAJ was originally part of the Java API for XML Messaging (JAXM), which was developed by the JSR 67 expert group. The final release of this specification (JAXM Version 1.0) provided two different but related facilities:
  • Core functionality concerned with manipulating SOAP messages in a generic way, together with the ability to send a SOAP message from one entity to another.
  • A higher-level messaging facility that included reliable delivery of messages and support for messaging profiles, which require SOAP messages to be constructed in specific ways.
During the maintenance cycle for JSR 67, it was decided to unbundle the low-level SOAP message creation features into a separate specification, thus creating SAAJ 1.1, leaving the higher-level features to form JAXM Version 1.1. At the same time, minor modifications were made to the API to remove a dependency that would otherwise have had the undesirable effect of making SAAJ 1.1 dependent on JAXM 1.1. The result is that it is possible to use SAAJ as a lightweight library for building and exchanging SOAP messages, without requiring the inclusion of JAXM 1.1, which provides facilities that go beyond the requirements of many web service clients. JAX-RPC, in particular, uses SAAJ to construct and decode SOAP messages, but it does not require reliable messaging and therefore is not dependent on the presence of a JAXM implementation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction to SAAJ
SAAJ, which stands for SOAP with Attachments API for Java, provides a convenient API for constructing SOAP messages without having to directly create the XML yourself. SAAJ was originally part of the Java API for XML Messaging (JAXM), which was developed by the JSR 67 expert group. The final release of this specification (JAXM Version 1.0) provided two different but related facilities:
  • Core functionality concerned with manipulating SOAP messages in a generic way, together with the ability to send a SOAP message from one entity to another.
  • A higher-level messaging facility that included reliable delivery of messages and support for messaging profiles, which require SOAP messages to be constructed in specific ways.
During the maintenance cycle for JSR 67, it was decided to unbundle the low-level SOAP message creation features into a separate specification, thus creating SAAJ 1.1, leaving the higher-level features to form JAXM Version 1.1. At the same time, minor modifications were made to the API to remove a dependency that would otherwise have had the undesirable effect of making SAAJ 1.1 dependent on JAXM 1.1. The result is that it is possible to use SAAJ as a lightweight library for building and exchanging SOAP messages, without requiring the inclusion of JAXM 1.1, which provides facilities that go beyond the requirements of many web service clients. JAX-RPC, in particular, uses SAAJ to construct and decode SOAP messages, but it does not require reliable messaging and therefore is not dependent on the presence of a JAXM implementation.
The formal specifications for both SAAJ 1.1 and JAXM 1.1 can be downloaded from http://jcp.org/jsr/detail/67.jsp. This chapter looks only at SAAJ and uses it as a convenient means of introducing SOAP messages; the more advanced messaging facilities provided by JAXM are covered in Chapter 4.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SAAJ Programming
Whereas JAX-RPC is concerned with allowing a client program to make a remote procedure call to a web service without exposing the underlying XML-based protocols that are used, SAAJ is a much lower-level API that is entirely concerned with the messages exchanged between the web service and its clients. Furthermore, while JAX-RPC applications look, for the most part, like ordinary Java applications making local method calls, an application that uses SAAJ needs to construct SOAP messages piece by piece and extract information from response messages. Using SAAJ requires much more work on the part of the developer than JAX-RPC, so why would you bother to use it? Here are some of the circumstances in which you might want to use SAAJ and its close relative JAXM instead of JAX-RPC:
  • JAX-RPC is convenient for accessing web services that present an RPC-like interface. However, the RPC model is not suitable for all services. In many cases, it is more convenient to simply send an XML message to a service, which the service interprets and then generates an XML response. The most commonly quoted example of this is a business-to-business service where the client sends a purchase order in the form of an XML document to which the service responds with a confirmation and an invoice, also encoded as an XML document. A simple service like this does not require method calls or arguments — all that is necessary is to exchange fragments of XML. SAAJ represents a convenient way to encode and decode the SOAP messages that will carry these XML documents.
  • Most services accessed using JAX-RPC are likely to be synchronous in nature, so that the service immediately processes the request and returns a reply to the client, which is blocked until the call completes. However, it is not always convenient or appropriate for the service to handle the request and reply immediately. Using the purchase order example again, the business that receives the purchase order may not be able to respond with a confirmation or an invoice immediately — perhaps not until the goods are in stock, or until it is verified that the initiator of the request has an account against which the goods can be ordered and that sufficient credit is available. For this type of business model, which is likely to be very common in the real world, it is more appropriate to think of the whole process as two separate operations that are not tightly coupled to each other and that the responding business might take anything from several seconds to several days to reply. To implement this type of loosely coupled messaging, it is appropriate to use JAXM, which is built on top of SAAJ and provides the ability to send and receive messages asynchronously.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SOAP Messages
The format of SOAP messages is defined by a note submitted to the World Wide Web Consortium (W3C) in May 2000 by a group of companies including Microsoft and IBM. This note, which describes Version 1.1 of SOAP and can be downloaded from http://www.w3.org/TR/SOAP, is not a formally adopted W3C specification but it is, nevertheless, the specification on which all existing SOAP implementations, including SAAJ, are based. The W3C is working on a formal definition of the next revision of SOAP, to be called Version 1.2. At the time of this writing, the SOAP 1.2 specification is available for public review, and Sun plans to include support for SOAP 1.2 in SAAJ (and JAX-RPC) when the specification is finalized.
SOAP defines a way to wrap information represented in XML so that it can be transmitted between peer entities that know how to interpret that information and, presumably, act on it to provide a service. Other than the fact that the useful content of the message (which is known as the payload) must be encoded in XML, SOAP does not mandate a particular set of XML elements and attributes to be used to represent primitive items of data (such as integers, floating-point numbers, and strings) in terms of XML constructs, although it does specify an encoding mechanism for these data types and others, the use of which is encouraged. In practice, these encoding rules, commonly referred to as "SOAP section 5 encoding," have become a de facto standard and are the default encoding used by JAX-RPC to represent method arguments and return values. Although detailed coverage of these encoding rules is outside the scope this book, there are several examples of their use in this chapter; you'll find a complete discussion of the SOAP encoding rules in Java and SOAP, by Robert Englander (O'Reilly). Applications are free to use privately defined encodings instead of the SOAP section 5 rules if they wish.
What SOAP does specify is the overall structure of a message, together with rules for wrapping SOAP messages when the underlying transport protocol is HTTP. There are two slightly different ways to construct a SOAP message depending on whether the message has any attachments (the meaning of which is defined later). The SOAP Version 1.1 specification covers only the case where there are no attachments and requires that a message be constructed as shown in Figure 3-1. The outermost layer of the message is a protocol-specific wrapper, the nature of which is defined in the specification only for HTTP and which we'll see later in this chapter. Inside this wrapper is the SOAP message itself, consisting of an envelope, a header part, a body part, and optional additional content.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SOAP Fault Handling
A SOAP fault is a specific type of XML element placed in the body of a reply message to convey status information or, more usually, to report a fault while processing the original request. SAAJ represents a fault using the SOAPFault interface that, since it must be a top-level element in the SOAP body, is derived from SOAPBodyElement (see Figure 3-4). The SOAP specification requires that there be no more than one SOAP fault in the message body. Faults can be mixed with other top-level elements if necessary.
SOAP faults have three attributes that can be set to provide information about the condition being reported. Each of these attributes has corresponding methods in the SOAPFault interface to allow its value to be set or retrieved:
Attribute
SOAPFault methods
Description
Fault code
getFaultCode( )
setFaultCode( )
A code that indicates the reason for reporting the fault. Applications may define their own private fault codes or use the set of standard values defined by the SOAP 1.1 specification (described later). All fault codes must be namespace-qualified.
Fault string
getFaultString( )
setFaultString( )
A human-readable description of the reason for the fault. The value of this attribute typically is written to a log file or displayed in a user interface.
Fault actor
getFaultActor( )
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SOAP Messages and MIME Headers
When a SOAP message is wrapped for transmission in HTTP (or another protocol, such as SMTP), suitable MIME headers must be created. At minimum, the wrapper must include the Content-Type and Content-Length headers along with the SOAPAction header that was described in Section 3.3.2, earlier in this chapter. Similarly, when a message is received, any MIME headers that accompany it must be extracted from the protocol-specific wrapper and be made part of the created SOAPMessage. The MIME headers associated with a SOAPMessage are held in an object of type javax.xml.soap.MimeHeaders .
In terms of the structure of an encapsulated SOAP message, the MIME headers logically appear outside the envelope (as shown in Figure 3-1), where they form the protocol-specific wrapper. In the case of a SOAP message with attachments, in addition to the headers in the outer wrapper, the SOAP message part and each of the attachment parts have their own collection of MIME headers that are distinct from those of the wrapper, as shown in Figure 3-2.
MimeHeader and MimeHeaders are two of four concrete classes in the java.xml.soap package. The MimeHeader class represents a single MIME header and contains the header name and its associated value, which are set at construction time and cannot subsequently be changed.
MimeHeaders is a collection of MimeHeader objects. When it is created, a MimeHeaders object is empty; headers can be added using one of the following methods:
public void addHeader(String headerName, String headerValue)
Creates a MimeHeader object with the given header name and value, and adds it to the collection of headers.
public void setHeader(String headerName, String headerValue)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SOAP with Attachments
A SOAP message constructed according to the SOAP 1.1 specification can only contain data encoded as XML. The SOAP with attachments specification defines an extension of the SOAP that allows additional data items — which may or may not be XML — to be transferred along with a SOAP message. SAAJ supports SOAP with attachments and provides a simple API that allows the transfer of arbitrary data. However, as we'll see, at the detailed level this interface is not quite as easy to use as it could be.
As a demonstration of the use of attachments, the book image web service uses the SAAJ API to return the cover images for one or more of the books that it knows about. To see how this works, start the client using the following command:
ant run-client-debug
When the list of book titles appears, select one or more of them by clicking on them with the mouse (hold down the Control key to select more than one), then press the "Fetch" button. The selected images will appear in the user interface, as shown in Figure 3-7, and the message used to deliver them will be written to the command window. Since the message contains the binary data for the images, you'll see some strange characters in the output window. Leaving out the image data itself, a typical message used to transfer three cover images is shown in Figure 3-8.
Figure 3-7: Using SOAP with attachments to transfer images
Figure 3-8: A SOAP with attachments message containing three attachments
Before we look at the SOAP with attachments message, let's briefly look at the request message that the client sends. This message (which does not have any attachments) contains an element called BookImageRequest that represents an array of strings, where each string is the title of a book. Here is what the body of the SOAP request looks like when requesting the cover images for three books:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
SOAP Headers
So far, we have only concerned ourselves with the body of a SOAP message and its attachments, both of which are intended solely for the ultimate destination of the message. A message can also include headers, which contain information that is related to the routing or processing of the message, but which are not part of the payload itself. SOAP itself does not define any standard headers, but there are specific uses of SOAP that do, some of which are discussed in Chapter 4. In this section, we'll look in a generic way at the facilities provided by SAAJ for creating and handling headers, and defer detailed discussion of real-world uses of this facility until Chapter 4.
Although the examples that we have shown so far involve only a client and a web service to which the client sends a SOAP message, in practice, a SOAP message may pass through one or more intermediate systems before reaching its ultimate destination. For the purposes of this discussion, an intermediate system is not like a network router, which is concerned only with passing a transport-level packet from node to node until it reaches a destination, but an application-level entity that receives a SOAP message, examines it, and either handles it or forwards it to another SOAP receiver for further processing.
As an example of the use of an intermediate system, suppose that a business wants to make it possible for other businesses to place stock orders by building a SOAP message that contains a purchase order, in response to which it expects confirmation of the order and payment details. Before the order is processed, it might be necessary to check that the initiator is known to the company and has a purchase account to which the transaction can be billed. In order to implement this, the business might separate the handling of the account check from the handling of the purchase order, as follows:
  1. When the client sends the purchase order, it is required to include a header that identifies it in a way that is determined by the business providing the service. In practice, this would probably involve the use of some secure mechanism, such as public key cryptography and the inclusion of a certificate to identify the client.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using SAAJ with Secure Connections
The web service examples used so far in this book have not attempted to provide any security measures to ensure that they can only be accessed by authorized users, or to provide some level of assurance to the client that the server to which it might be about to pass sensitive information is the one to which it thinks it is connected. At the time of this writing, security for web services is the subject of several in-progress JSRs, such as JSR 105 (XML Digital Signature APIs; see http://jcp.org/jsr/detail/105.jsp) and JSR 106 (XML Digital Encryption APIs; see http://jcp.org/jsr/detail/106.jsp). Until these JSRs are completed and their implementations become part of the Java platform, you can still make use of the authentication mechanisms already provided for HTTP to add a level of security to your service. In this section, you'll see how to configure the client and server parts of the service to use both HTTP basic authentication, which is relatively weak, and HTTPS, which is much more robust but is slightly more difficult to set up.
HTTP basic authentication is a simple mechanism that requires the client to supply a username and password to gain access to a service. The authentication information is encoded and sent in an HTTP header to the server, which can then verify whether the user should have access to the service at the URL specified in the request. Although it is easy to configure basic authentication, it is a very weak mechanism because the data exchanged by the client and server is not encrypted and there is no protection against unauthorized modification. Furthermore, the algorithm used to encode the username and password is trivial, thus making it a simple matter for a snooper to discover what they are. Nevertheless, in an internal corporate network, basic authentication may be sufficient.
To demonstrate how to use basic authentication, we'll add it to the book image web service. Configuring basic authentication requires three steps:
  1. Define the role or roles that are allowed access to some or all of the web service and the set of users that belong to those roles.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: JAXM
SAAJ is a convenient API that allows applications to exchange SOAP messages containing information encoded in XML, together with arbitrary data held in message attachments. Although it is useful on its own, SAAJ is also the basis for JAX-RPC and for the Java API for XML Messaging (JAXM). This chapter looks at the features that JAXM adds to SAAJ and describes how to configure and use the JAXM reference implementation.
Although JAXM is part of the Java Web Services Developers Pack, it is not one of the APIs that was selected for inclusion in Version 1.4 of the J2EE platform. The examples in this chapter can therefore only be used with the JWSDP. JAXM may be integrated into a future release of J2EE, but at the time of this writing, there is no commitment on Sun's part to do this.
SAAJ allows you to construct SOAP messages and send them directly and synchronously to a web service. JAXM builds on SAAJ to provide a higher-level API with the following additional features:
Messaging profiles
The SOAP messages returned by the SAAJ MessageFactory consist of an empty body and an empty header. However, there are established uses of SOAP that make use of message headers to convey information from the message sender to the receiver, or to intermediate nodes that the message might traverse along its delivery path. JAXM provides the concept of messaging profiles , where a profile represents a specific and standardized way of constructing a SOAP message, such as the ebXML Message Service. A JAXM messaging profile is represented by a profile-specific MessageFactory that can build SOAP messages according to the rules applicable to the profile.
Asynchronous messaging
Using SAAJ, you can only send a message directly to a service and then wait for the service to send a reply. This mode of operation is well-suited to RPC-style interaction, in which the server is able to reply almost immediately to an incoming message. In many cases, however, it is not possible to operate in this way. If a client submits a purchase order to a company's online business web service, for example, it may not be possible to respond immediately with an order confirmation or an invoice for payment. In these circumstances, it is useful to be able to simply send a message and be prepared to receive a reply at a later time. JAXM supports this by providing several asynchronous messaging modes, described in Section 4.1.1 next.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JAXM Overview
SAAJ allows you to construct SOAP messages and send them directly and synchronously to a web service. JAXM builds on SAAJ to provide a higher-level API with the following additional features:
Messaging profiles
The SOAP messages returned by the SAAJ MessageFactory consist of an empty body and an empty header. However, there are established uses of SOAP that make use of message headers to convey information from the message sender to the receiver, or to intermediate nodes that the message might traverse along its delivery path. JAXM provides the concept of messaging profiles , where a profile represents a specific and standardized way of constructing a SOAP message, such as the ebXML Message Service. A JAXM messaging profile is represented by a profile-specific MessageFactory that can build SOAP messages according to the rules applicable to the profile.
Asynchronous messaging
Using SAAJ, you can only send a message directly to a service and then wait for the service to send a reply. This mode of operation is well-suited to RPC-style interaction, in which the server is able to reply almost immediately to an incoming message. In many cases, however, it is not possible to operate in this way. If a client submits a purchase order to a company's online business web service, for example, it may not be possible to respond immediately with an order confirmation or an invoice for payment. In these circumstances, it is useful to be able to simply send a message and be prepared to receive a reply at a later time. JAXM supports this by providing several asynchronous messaging modes, described in Section 4.1.1 next.
More robust message delivery
SAAJ requires both the sender and receiver of a message to be active at the same time and works only if it is possible to make a direct connection between the two (although transparent hops — i.e., proxies — are supported in the same way as they are by the generic HTTP support in the JRE). JAXM removes both of these restrictions by providing an intermediary
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Providers and Asynchronous Messaging
The asynchronous messaging and reliable delivery features of JAXM are implemented by a messaging provider. The specification itself says very little about the provider, other than to describe the API needed to access it, leaving the details to be determined by implementations. In practice, application code is almost unaffected by the presence of a provider, but it is very important to understand how to configure the provider and how to deploy the application with the appropriate settings required to access it. In this section, we look at the API that application code uses to work with the provider, and at how to configure the provider included with the JAXM reference implementation.
When a message provider is in use, the logical flow of a message is still directly from the sender to the receiver, but the actual flow is somewhat different, as shown in Figure 4-4.
Figure 4-4: Logical and actual message flow when using a messaging provider
In order to send messages, the sender first connects to the local provider and determines whether it supports the messaging profile that it wants to use; if so, it obtains a MessageFactory for that profile. Each message is then handled as follows:
  1. The sender creates a SOAP message using the SAAJ API with the MessageFactory for the selected messaging profile.
  2. The message is sent to the local provider. This operation returns control to the caller as soon as the provider receives the message, and the sender is free to continue with other processing.
  3. The provider stores the message in its outgoing queue.
  4. A separate thread handles queued messages, dispatching each of them in turn to the receiving provider. If the receiving provider is not accessible, the message is left in the queue and retried later.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Example JAXM Application
In order to demonstrate the JAXM APIs and show you how to set up the JAXM provider configuration, we'll look at the implementation of a very simple web service that simply accepts a message and returns it to its sender, having added an XML element containing the date and time at which the message was processed. The process of returning the message requires the receiver to explicitly address the message to its originator and send it back via its own local provider. In other words, each time this service is used, two asynchronous messages are sent, one in each direction.
Since this is a JAXM example, both the sender and the receiver are implemented as servlets in a web container. Both of them need to be able to receive SOAP messages and dispatch them to application code. In Chapter 3, we used a private class called SAAJServlet as the base class for our example web service, but in this chapter, we are going to use the class javax.xml.messaging.JAXMServlet instead. These two servlets are virtually identical — the only real difference between them is that JAXMServlet is included as part of the JAXM API and should therefore be available in all JAXM implementations, whereas SAAJServlet is a private class developed from example code in the JWSDP distribution. We could, of course, have used JAXMServlet in Chapter 3 instead of creating SAAJServlet, but to do so would have introduced a dependency on JAXM, which we wanted to avoid. Like SAAJServlet, JAXMServlet delivers received SOAP messages via the onMessage( ) method, where the application will implement its message handling.
In previous examples, in which the message sender was a freestanding application, we could run it by simply starting the application from the command line. When the message sender is implemented as a servlet, however, we have to take a different approach. We'll implement the servlet's doGet( ) method so that it sends a message to the receiver whenever it is invoked. This allows us to run the example by pointing a web browser at the appropriate URL; this also gives us somewhere to display the message that the receiver returns to us. We don't have a similar issue with the message receiver, which is also deployed as a servlet derived from
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JAXM Configuration
You have now seen and deployed all of the code for both the sender and receiver parts of the JAXM message echo example. If, however, you were to start your web browser and point it at http://localhost:8080/SOAPRPSender/request, which is the URL that causes the sender servlet to transmit a message, you would find that after about 30 seconds, the sender would give up waiting for a reply from the receiver and an error page would be displayed by the browser. Although all of the code is in place, the proper JAXM configuration has not been set up to allow the providers to exchange messages. In this section, we look at how to configure the JAXM reference implementation.
A message traveling from the sending servlet to the receiver has to make three hops:
  1. From the sender to the local provider
  2. From the local provider to the remote provider
  3. From the remote provider to the receiving servlet
We saw earlier that a JAXM client logically connects to its local provider using the ProviderConnectionFactory createConnection( ) method, but we didn't see how the provider itself is located. This information is held in a file called client.xml, which must be located in the CLASSPATH of the JAXM client. Since both the sender and the receiver servlets in this example are deployed as web applications, their client.xml files should be placed in the WEB-INF/classes directory of their WAR files, as shown in the following listing of the files that make up the web archive for the SOAPRPSender servlet:
 META-INF/MANIFEST.MF
 WEB-INF/classes/ora/jwsnut/chapter4/soaprpsender/SOAPRPSenderServlet.class
 WEB-INF/classes/client.xml
 WEB-INF/web.xml
A full description of the client.xml file will be found in Chapter 8. The content of the client.xml file used by the SOAPRPSender servlet is shown in Example 4-6, in which the line numbers on the left have been added for ease of reference only.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The SOAP-RP Profile
The SOAP-RP profile is an implementation of the SOAP WS-Routing specification (formerly known as the SOAP Routing Protocol), which can be downloaded from http://msdn.microsoft.com/ws/2001/10/Routing. Although a full discussion of the specification is outside the scope of this book, this section contains a brief overview and a description of the API that JAXM provides to allow the construction of messages that conform to the specification.
SOAP-RP defines a SOAP header and a set of rules to be followed that enable a SOAP message to be routed from a sender, through zero or more intermediate systems to its final destination. The SOAP-RP header, which is called path, contains child elements from the set listed in Table 4-4.
Table 4-4: SOAP-RP header elements
Element
Description
to
Contains the URI of the ultimate destination of the message. This element is added by the sender and cannot be changed as the message passes through intermediate systems.
from
Contains a URI that identifies the sender of the message.
fwd
If present, this tag contains zero or more URIs that define a list of intermediate systems that must be visited before the message is delivered to its final recipient. All of the systems in this list must be visited in the order in which they appear. If this is not possible, the message is discarded and a fault is returned (see the fault element).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The ebXML Profile
The ebXML initiative aims to create a framework for applications that allow organizations to carry out electronic business by exchanging XML-based messages. The ebXML Transport, Routing, and Packaging (ebXML-TRP) specification (lcoated at http://www.ebxml.org/specs/ebMS.pdf) defines the packaging model for ebXML messages, which is based on SOAP with attachments and is therefore compatible with both SAAJ and JAXM. This section briefly describes the ebXML packaging model and looks at how it is supported by the JAXM ebXML profile. The ebXML profile implements Version 1.0 of the ebXML-TRP specification.
Like WS-Routing, ebXML-TRP uses SOAP headers to carry protocol information. Unlike WS-Routing, however, ebXML-TRP also defines elements that may be added to the SOAP message body. Many of the features described in the ebXML-TRP specification are optional, so we'll restrict ourselves to briefly discussing just the mandatory parts of the specification, which are the only parts actually provided in the JAXM reference implementation. For a definitive description, refer to the ebXML-TRP specification itself.
ebXML-TRP considers a SOAP message to be made up of two separate parts:
The header container
Despite its name, the header container corresponds to the entire SOAP part of the message and therefore consists of both the SOAP header and the SOAP body. The specification defines six elements that may appear in the header, and four that can be used in the message body. The JAXM ebXML profile supports only one header element and one body element, since the others are optional.
Payload containers
An ebXML-TRP message may have zero or more payload containers that carry information that supplements the XML in the header container. Each payload container is realized as a SOAP message attachment; therefore, it can carry data of any type that has a MIME representation, such as an image or an XML document. Since SAAJ already provides the ability to add attachments to a message, no additional API is required in the ebXML profile to handle payload containers. However, the application must ensure that each payload container in the message has a corresponding reference in the ebXML-TRP
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: WSDL
Content preview·