BUY THIS BOOK
Add to Cart

Print Book $34.95


Add to Cart

Print+PDF $45.44

Add to Cart

PDF $27.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint or License this content?


Programming Web  Services with SOAP
Programming Web Services with SOAP By James Snell, Doug Tidwell, Pavel Kulchenko
December 2001
Pages: 260

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing Web Services
To make best use of web services and SOAP, you must have a firm understanding of the principles and technologies upon which they stand. This chapter is an introduction to a variety of new technologies, approaches, and ideas for writing web-based applications to take advantage of the web services architecture. SOAP is one part of the bigger picture described in this chapter, and you'll learn how it relates to the other technologies described in this book: the Web Service Description Language (WSDL), the Web Service Inspection Language (WS-IL), and the Universal Description, Discovery, and Integration (UDDI) services.
Before we go any further, let's define the basic concept of a "web service." A web service is a network accessible interface to application functionality, built using standard Internet technologies. This is illustrated in Figure 1-1.
Figure 1-1: A web service allows access to application code using standard Internet technologies
In other words, if an application can be accessed over a network using a combination of protocols like HTTP, XML, SMTP, or Jabber, then it is a web service. Despite all the media hype around web services, it really is that simple.
Web services are nothing new. Rather, they represent the evolution of principles that have guided the Internet for years.
As Figure 1-1 and Figure 1-2 illustrate, a web service is an interface positioned between the application code and the user of that code. It acts as an abstraction layer, separating the platform and programming-language-specific details of how the application code is actually invoked. This standardized layer means that any language that supports the web service can access the application's functionality.
Figure 1-2: Web services provide an abstraction layer between the application client and the application code
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?
Before we go any further, let's define the basic concept of a "web service." A web service is a network accessible interface to application functionality, built using standard Internet technologies. This is illustrated in Figure 1-1.
Figure 1-1: A web service allows access to application code using standard Internet technologies
In other words, if an application can be accessed over a network using a combination of protocols like HTTP, XML, SMTP, or Jabber, then it is a web service. Despite all the media hype around web services, it really is that simple.
Web services are nothing new. Rather, they represent the evolution of principles that have guided the Internet for years.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Service Fundamentals
As Figure 1-1 and Figure 1-2 illustrate, a web service is an interface positioned between the application code and the user of that code. It acts as an abstraction layer, separating the platform and programming-language-specific details of how the application code is actually invoked. This standardized layer means that any language that supports the web service can access the application's functionality.
Figure 1-2: Web services provide an abstraction layer between the application client and the application code
The web services that we see deployed on the Internet today are HTML web sites. In these, the application services—the mechanisms for publishing, managing, searching, and retrieving content—are accessed through the use of standard protocols and data formats: HTTP and HTML. Client applications (web browsers) that understand these standards can interact with the application services to perform tasks like ordering books, sending greeting cards, or reading news.
Because of the abstraction provided by the standards-based interfaces, it does not matter whether the application services are written in Java and the browser written in C++, or the application services deployed on a Unix box while the browser is deployed on Windows. Web services allow for cross-platform interoperability in a way that makes the platform irrelevant.
Interoperability is one of the key benefits gained from implementing web services. Java and Microsoft Windows-based solutions have typically been difficult to integrate, but a web services layer between application and client can greatly remove friction.
There is currently an ongoing effort within the Java community to define an exact architecture for implementing web services within the framework of the Java 2 Enterprise Edition specification. Each of the major Java technology providers (Sun, IBM, BEA, etc.) are all working to enable their platforms for web services support.
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 Web Service Technology Stack
The web services architecture is implemented through the layering of five types of technologies, organized into layers that build upon one another (Figure 1-5).
Figure 1-5: The web service technology stack
It should come as no surprise that this stack is very similar to the TCP/IP network model used to describe the architecture of Internet-based applications (Figure 1-6).
Figure 1-6: The TCP/IP network model
The additional packaging, description, and discovery layers in the web services stack are the layers essential to providing Just-In-Time Integration capability and the necessary platform-neutral programming model.
Because each part of the web services stack addresses a separate business problem, you only have to implement those pieces that make the most sense at any given time. When a new layer of the stack is needed, you do not have to rewrite significant chunks of your infrastructure just to support a new form of exchanging information or a new way of authenticating users.
The goal is total modularization of the distributed computing environment as opposed to recreating the large monolithic solutions of more traditional distributed platforms like Java, CORBA, and COM. Modularity is particularly necessary in web services because of the rapidly evolving nature of the standards. This is shown in the sample CodeShare application of Chapter 7, where we don't use the discovery layer, but we do draw in another XML standard to handle security.
The layers of the web services stack do not provide a complete solution to many business problems. For instance, they don't address security, trust, workflow, identity, or many other business concerns. Here are some of the most important standardization initiatives currently being pursued in these areas:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application
The application layer is the code that implements the functionality of the web service, which is found and accessed through the lower layers in the stack.
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 Peer Services Model
The peer services model is a complimentary but alternative view of the web services architecture. Based on the peer-to-peer (P2P) architecture, every member of a group of peers shares a common collection of services and resources. A peer can be a person, an application, a device, or another group of peers operating as a single entity.
While it may not be readily apparent, the same fundamental web services components are present as in the peer services architecture. There are both service providers and service consumers, and there are service registries. The distinction between providers and consumers, however, is not as clear-cut as in the web services case. Depending on the type of service or resource that the peers are sharing, any individual peer can play the role of both a service provider and a service consumer. This makes the peer services model more dynamic and flexible.
Instant Messaging is the most widely utilized implementation of the peer services model. Every person that uses instant messaging is a peer. When you receive an invitation to chat with somebody, you are playing the role of a service provider. When you send an invitation out to chat with somebody else, you are playing the role of a service consumer. When you log on to the Instant Messaging Server, the server is playing the role of the service registry—that is, the Instant Messaging Server keeps track of where you currently are and what your instant messaging capabilities are. Figure 1-7 illustrates this.
Figure 1-7: The peer web services model simply applies the concepts of the web services architecture in a peer-to-peer network
Peer services and web services emerged and evolved separately from one another, and accordingly make use of different protocols and technologies to implement their respective models. Peer web services tie the two together by unifying the technologies, the protocols, and the models into a single comprehensive big picture. The implementation of a peer web service will be the central focus of Chapter 7.
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: Introducing SOAP
SOAP's place in the web services technology stack is as a standardized packaging protocol for the messages shared by applications. The specification defines nothing more than a simple XML-based envelope for the information being transferred, and a set of rules for translating application and platform-specific data types into XML representations. SOAP's design makes it suitable for a wide variety of application messaging and integration patterns. This, for the most part, contributes to its growing popularity.
This chapter explains the parts of the SOAP standard. It covers the message format, the exception-reporting mechanism (faults), and the system for encoding values in XML. It discusses using SOAP over transports that aren't HTTP, and concludes with thoughts on the future of SOAP. You'll learn what SOAP does and how it does it, and get a firm understanding of the flexibility of SOAP. Later chapters build on this to show how to program with SOAP using toolkits that abstract details of the XML.
SOAP is XML. That is, SOAP is an application of the XML specification. It relies heavily on XML standards like XML Schema and XML Namespaces for its definition and function. If you are not familiar with any of these, you'll probably want to get up to speed before continuing with the information in this chapter (you can find information about each of these specifications at the World Wide Web Consortium's web site at http://www.w3c.org). This book assumes you are familiar with these specifications, at least on a cursory level, and will not spend time discussing them. The only exception is a quick introduction to the XML Schema data types in Appendix B.
XML messaging is where applications exchange information using XML documents (see Figure 2-1). It provides a flexible way for applications to communicate, and forms the basis of SOAP.
A message can be anything: a purchase order, a request for a current stock price, a query for a search engine, a listing of available flights to Los Angeles, or any number of other pieces of information that may be relevant to a particular application.
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 and XML
SOAP is XML. That is, SOAP is an application of the XML specification. It relies heavily on XML standards like XML Schema and XML Namespaces for its definition and function. If you are not familiar with any of these, you'll probably want to get up to speed before continuing with the information in this chapter (you can find information about each of these specifications at the World Wide Web Consortium's web site at http://www.w3c.org). This book assumes you are familiar with these specifications, at least on a cursory level, and will not spend time discussing them. The only exception is a quick introduction to the XML Schema data types in Appendix B.
XML messaging is where applications exchange information using XML documents (see Figure 2-1). It provides a flexible way for applications to communicate, and forms the basis of SOAP.
A message can be anything: a purchase order, a request for a current stock price, a query for a search engine, a listing of available flights to Los Angeles, or any number of other pieces of information that may be relevant to a particular application.
Figure 2-1: XML messaging
Because XML is not tied to a particular application, operating system, or programming language, XML messages can be used in all environments. A Windows Perl program can create an XML document representing a message, send it to a Unix-based Java program, and affect the behavior of that Java program.
The fundamental idea is that two applications, regardless of operating system, programming language, or any other technical implementation detail, may openly share information using nothing more than a simple message encoded in a way that both applications understand. SOAP provides a standard way to structure XML messages.
XML messaging, and therefore SOAP, has two related applications: RPC and EDI. Remote Procedure Call (RPC) is the basis of distributed computing, the way for one program to make a procedure (or function, or method, call it what you will) call on another, passing arguments and receiving return values. Electronic Document Interchange (EDI) is basis of automated business transactions, defining a standard format and interpretation of financial and commercial documents and messages.
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
A SOAP message consists of an envelope containing an optional header and a required body, as shown in Figure 2-2. The header contains blocks of information relevant to how the message is to be processed. This includes routing and delivery settings, authentication or authorization assertions, and transaction contexts. The body contains the actual message to be delivered and processed. Anything that can be expressed in XML syntax can go in the body of a message.
Figure 2-2: The SOAP message structure
The XML syntax for expressing a SOAP message is based on the http://www.w3.org/2001/06/soap-envelope namespace. This XML namespace identifier points to an XML Schema that defines the structure of what a SOAP message looks like.
If you were using document-style SOAP, you might transfer a purchase order with the XML in Example 2-2.
Example 2-2. A purchase order in document-style SOAP
<s:Envelope 
 xmlns:s="http://www.w3.org/2001/06/soap-envelope">
    <s:Header>
       <m:transaction xmlns:m="soap-transaction"
                      s:mustUnderstand="true">
           <transactionID>1234</transactionID>
       </m:transaction>
    </s:Header>
    <s:Body>
       <n:purchaseOrder xmlns:n="urn:OrderService">
          <from><person>Christopher Robin</person>
                <dept>Accounting</dept></from>
          <to><person>Pooh Bear</person>
               <dept>Honey</dept></to>
          <order><quantity>1</quantity>
                 <item>Pooh Stick</item></order>
       </n:purchaseOrder>
    </s:Body>
</s:Envelope>
This example illustrates all of the core components of the SOAP Envelope specification. There is the <s:Envelope>, the topmost container that comprises the SOAP message; the optional <s:Header>, which contains additional blocks of information about how the body payload is to be processed; and the mandatory <s:Body> element that contains the actual message to be processed.
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 Faults
A SOAP fault (shown in Example 2-8) is a special type of message specifically targeted at communicating information about errors that may have occurred during the processing of a SOAP message.
Example 2-8. SOAP fault
<s:Envelope xmlns:s="...">
   <s:Body>
      <s:Fault>
       <faultcode>Client.Authentication</faultcode>
       <faultstring>
          Invalid credentials
       </faultstring>
       <faultactor>http://acme.com</faultactor>
       <details>
          <!-- application specific details -->
       </details>
      </s:Fault>
   </s:Body>
</s:Envelope>
The information communicated in the SOAP fault is as follows:
The fault code
An algorithmically generated value for identifying the type of error that occurred. The value must be an XML Qualified Name, meaning that the name of the code only has meaning within a defined XML namespace.
The fault string
A human-readable explanation of the error.
The fault actor
The unique identifier of the message processing node at which the error occurred (actors will be discussed later).
The fault details
Used to express application-specific details about the error that occurred. This must be present if the error that occurred is directly related to some problem with the body of the message. It must not be used, however, to express information about errors that occur in relation to any other aspect of the message process.
SOAP defines four standard types of faults that belong to the http://www.w3.org/2001/06/soap-envelope namespace. These are described here:
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 Message Exchange Model
Processing a SOAP message involves pulling apart the envelope and doing something with the information that it carries. SOAP defines a general framework for such processing, but leaves the actual details of how that processing is implemented up to the application.
What the SOAP specification does have to say about message processing deals primarily with how applications exchange SOAP messages. Section 2 of the specification outlines a very specific message exchange model.
At the core of this exchange model is the idea that while a SOAP message is fundamentally a one-way transmission of an envelope from a sender to a receiver, that message may pass through various intermediate processors that each in turn do something with the message. This is analogous to a Unix pipeline, where the output of one program becomes the input to another, and so on until you get the output you want.
A SOAP intermediary is a web service specially designed to sit between a service consumer and a service provider and add value or functionality to the transaction between the two. The set of intermediaries that the message travels through is called the message path. Every intermediary along that path is known as an actor.
The construction of a message path (the definition of which nodes a message passes through) is not covered by the SOAP specification. Various extensions to SOAP, such as Microsoft's SOAP Routing Protocol (WS-Routing) have emerged to fill that gap, but there is still no standard (de facto or otherwise) method of expressing the message path. We cover WS-Routing later.
What SOAP does specify, however, is a mechanism of identifying which parts of the SOAP message are intended for processing by specific actors in its message path. This mechanism is known as "targeting" and can only be used in relation to header blocks (the body of the SOAP envelope cannot be explicitly targeted at a particular node).
A header block is targeted to a specific actor on its message path through the use of the special
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 SOAP for RPC-Style Web Services
RPC is the most common application of SOAP at the moment. The following sections show how method calls and return values are encoded in SOAP message bodies.
The rules for packaging an RPC request in a SOAP envelope are simple:
  • The method call is represented as a single structure with each in or in-out parameter modeled as a field in that structure.
  • The names and physical order of the parameters must correspond to the names and physical order of the parameters in the method being invoked.
This means that a Java method with the following signature:
String checkStatus(String orderCode, 
                   String customerID);
can be invoked with these arguments:
result = checkStatus("abc123", "Bob's Store")
using the following SOAP envelope:
<s:Envelope xmlns:s="...">
  <s:Body>
    <checkStatus xmlns="..."
                 s:encodingStyle="http://www.w3.org/2001/06/soap-encoding">
      <orderCode xsi:type="string">abc123</orderCode>
      <customerID xsi:type="string">
        Bob's Store
      </customerID>
    </checkStatus>
  </s:Body>
</s:Envelope>
The SOAP RPC conventions do not require the use of the SOAP Section 5 encoding style and xsi:type explicit data typing. They are, however, widely used and will be what we describe.
Method responses are similar to method calls in that the structure of the response is modeled as a single structure with a field for each in-out or out parameter in the method signature. If the checkStatus method we called earlier returned the string new, the SOAP response might be something like Example 2-13.
Example 2-13. Response to the method call
<s:Envelope xmlns:s="...">
  <s:Body>
    <checkStatusResponse 
     s:encodingStyle="http://www.w3.org/2001/06/soap-encoding">
      <return xsi:type="xsd:string">new</return>
    </checkStatusResponse>
  </SOAP:Body>
</SOAP: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!
SOAP's Data Encoding
The first part of the SOAP specification outlines a standard envelope format for packaging data. The second part of the specification (specifically, Section 5) outlines one possible method of serializing the data intended for packaging. These rules outline in specific detail how basic application data types are to be mapped and encoded into XML format when embedded into a SOAP Envelope.
The SOAP specification introduces the SOAP encoding style as "a simple type system that is a generalization of the common features found in type systems in programming languages, databases, and semi-structured data." As such, these encoding rules can be applied in nearly any programming environment regardless of the minor differences that exist between those environments.
Encoding styles are completely optional, and in many situations not useful (recall the purchase order example we gave earlier in this chapter, where it made sense to ship a document and not an encoded method call/response). SOAP envelopes are designed to carry any arbitrary XML documents no matter what the body of the message looks like, or whether it conforms to any specific set of data encoding rules. The Section 5 encoding rules are offered only as a convenience to allow applications to dynamically exchange information without a priori knowledge of the types of information to be exchanged.
Before continuing, it is important to gain a firm understanding of the vocabulary used to describe the encoding process. Of particular importance are the terms value and accessor .
A value represents either a single data unit or combination of data units. This could be a person's name, the score of a football game, or the current temperature. An accessor represents an element that contains or allows access to a value. In the following, firstname is an accessor, and Joe is a value:
<firstname> Joe </firstname>
A compound value represents a combination of two or more accessors grouped as children of a single accessor, and is demonstrated in Example 2-14.
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 Data Types
The data types supported by the SOAP encoding style are the data types defined by the "XML Schema data types" specification. All data types used within a SOAP-encoded block of XML must either be taken directly from the XML Schema specification or derived from types therein.
SOAP encoding provides two alternate syntaxes for expressing instances of these data types within the SOAP envelope. Example 2-19 shows two equivalent expressions of an integer equaling the value "36".
Example 2-19. Alternate SOAP encoding syntaxes for typing values
<SOAP-ENC:int>36</SOAP-ENC:int>
<value xsi:type="xsd:int">36</value>
The first method is what is known as an anonymous accessor , and is commonly found in SOAP encoded arrays (as we will see a little later in this chapter). It's "anonymous" because the accessor's name is its type, rather than a meaningful identification for the value. The second approach is the named accessor syntax that we've already seen. Either is valid since they both can be directly linked back to the XML Schema data types.
The values a program works with are stored in memory. Variables are how programming languages let you manipulate those values in memory. Two different variables might have the same value; for instance, two integer variables could both be set to the value 42. The SOAP XML encoding for this would use single-reference XML, as in Example 2-20.
Example 2-20. Two integer variables set to 42
<SOAP-ENC:int>42</SOAP-ENC:int>
<SOAP-ENC:int>42</SOAP-ENC:int>
Sometimes, though, you need to indicate that two separate variables are stored in the same piece of memory. For instance, if this subroutine call is going to be XML encoded for SOAP, you'll need to identify the first and second parameters as being the same:
tweak(&i, &i);
You do this with Section 5's encoding rules using multiple-reference types. That is, you use the
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 Transports
As mentioned before, SOAP fits in on the web services technology stack as a standardized packaging protocol layered on top of the network and transport layers. As a packaging protocol, SOAP does not care what transport protocols are used to exchange the messages. This makes SOAP extremely flexible in how and where it is used.
As an illustration of this flexibility, SOAP::Lite—the Perl-based SOAP web services implementation written by Pavel Kulchenko—supports the ability to exchange SOAP messages through HTTP, FTP, raw TCP, SMTP, POP3, MQSeries, and Jabber. We'll show SOAP over Jabber in Chapter 3.
Because of its pervasiveness on the Internet, HTTP is by far the most common transport used to exchange SOAP messages. The SOAP specification even goes so far as to give special treatment to HTTP within the specification itself—outlining in specific detail how the semantics of the SOAP message exchange model map onto HTTP.
SOAP-over-HTTP is a natural match with SOAP's RPC (request-response) conventions because HTTP is a request-response-based protocol.The SOAP request message is posted to the HTTP server with the HTTP request, and the server returns the SOAP response message in the HTTP response (see Figure 2-5).
Figure 2-5: SOAP request messages are posted to the HTTP server and response messages are returned over the same HTTP connection
Example 2-30 and Example 2-31 illustrate an HTTP request and HTTP response messages that contain a SOAP message.
Example 2-30. HTTP request containing a SOAP message
POST /StockQuote HTTP/1.1
Content-Type: text/xml
Content-Length: nnnn
SOAPAction: "urn:StockQuote#GetQuote"

<s:Envelope xmlns:s="http://www.w3.org/2001/06/soap-envelope">
  ...
</s:Envelope>
Example 2-31. HTTP response containing a SOAP message
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: Writing SOAP Web Services
In Chapter 2, we looked under the hood of SOAP at the XML underneath. In this chapter, we demonstrate how to create, deploy, and use SOAP web services using toolkits for Java, Perl, and Microsoft's new .NET platform. We cover the installation, configuration, and use of SOAP::Lite for Perl, Apache SOAP for Java, and Microsoft .NET for C#.
The task of creating and deploying web services is really not all that difficult, nor is it all that different than what developers currently do in more traditional web applications. The tendency on all platforms is to automate more and more of the gory details and tedious work in creating web services. Most programmers don't need to know the exact details of encodings and envelopes; instead, they'll simply use a SOAP toolkit such as those described here.
In Chapter 1, we touched briefly on the fact that a web service consists of three components: a listener to receive the message, a proxy to take that message and translate it into an action to be carried out (such as invoking a method on a Java object), and the application code to implement that action.
The listener and proxy components should be completely transparent to the application code, if properly implemented. The ideal situation in most cases is that the code doesn't even know it is being invoked through a web service interface, but that is not always possible, or desirable.
A good example of a seamless, simple web services implementation is the SOAP::Lite for Perl written by Pavel Kulchenko. This package allows any installed Perl module to be automatically deployed as a web service without any work on the part of the module developer. The proxy can automatically load and invoke any subroutine in any module.
There is a surprisingly long list of SOAP implementations available to developers. In this book, we have chosen to focus on three of the most popular tools: Apache SOAP for Java, SOAP::Lite for Perl, and Microsoft .NET. No matter which toolkit you use, the fundamental process of creating, deploying, and using SOAP web services is the same.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Services Anatomy 101
In Chapter 1, we touched briefly on the fact that a web service consists of three components: a listener to receive the message, a proxy to take that message and translate it into an action to be carried out (such as invoking a method on a Java object), and the application code to implement that action.
The listener and proxy components should be completely transparent to the application code, if properly implemented. The ideal situation in most cases is that the code doesn't even know it is being invoked through a web service interface, but that is not always possible, or desirable.
A good example of a seamless, simple web services implementation is the SOAP::Lite for Perl written by Pavel Kulchenko. This package allows any installed Perl module to be automatically deployed as a web service without any work on the part of the module developer. The proxy can automatically load and invoke any subroutine in any module.
There is a surprisingly long list of SOAP implementations available to developers. In this book, we have chosen to focus on three of the most popular tools: Apache SOAP for Java, SOAP::Lite for Perl, and Microsoft .NET. No matter which toolkit you use, the fundamental process of creating, deploying, and using SOAP web services is the same.
A comprehensive and up-to-date listing of all known SOAP implementations and toolkits can be found by visiting either http://www.soaplite.com or http://www.soapware.org. There are SOAP toolkits for all the popular programming languages and environments (Java, C#, C++, C, Perl, PHP, and Python, just to name a few).
The integration of SOAP toolkits varies with the transport layer. Some implement their own HTTP servers. Some expect to be installed as part of a particular web server, so that rather than serving up a web page, the HTTP daemon hands the SOAP message to the toolkit's proxy component, which does the work of invoking the code behind the web service (see Figure 3-1).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Web Services in Perl with SOAP::Lite
Perl, like most languages, hides the programmer from the complexities of SOAP with a toolkit. The SOAP::Lite toolkit is one of the most complete implementations of SOAP available, supporting both Versions 1.1 and 1.2 of SOAP. It has strong support for alternate transports (FTP, HTTP, IO, Jabber, SMTP, POP3, TCP, and MQSeries), which we'll use later to demonstrate SOAP over Jabber.
SOAP::Lite, like many Perl modules, is available on the Comprehensive Perl Archive Network (CPAN). CPAN is a network of web and FTP sites with identical content—the source to thousands of Perl modules. You can access CPAN through a Perl command-line client or via the Web at http://www.cpan.org. See http://www.cpan.org/misc/cpan-faq.html#How_install_Perl_modules for information on installing Perl modules.
Example 3-1 shows a sample installation of SOAP::Lite using the interactive CPAN command-line shell.
Example 3-1. Installing SOAP::Lite with the CPAN shell
C:\book>perl -MCPAN -e shell
cpan shell—CPAN exploration and modules installation (v1.59_54)
cpan> install SOAP::Lite
(You may be walked through configuring the CPAN shell if this is the first time you have run it.) The CPAN shell will connect to a CPAN site and download the source for SOAP::Lite. Once downloaded, the shell will attempt to build the module. SOAP::Lite has a series of interactive steps to configure the module, shown in Example 3-2. You can either use a default configuration or manually select from a menu of options to build a custom configuration.
Example 3-2. SOAP::Lite's interactive configuration
We are about to install SOAP::Lite and for your convenience will provide you with list 
of modules and prerequisites, so you'll be able to choose only modules you need for 
your configuration.

XMLRPC::Lite, UDDI::Lite, and XML::Parser::Lite are included by default. Installed 
transports can be used for both SOAP::Lite and XMLRPC::Lite.

Client (SOAP::Transport::HTTP::Client)                               [yes]
Client HTTPS/SSL support 
   (SOAP::Transport::HTTP::Client, require OpenSSL)                   [no]
Client SMTP/sendmail support (SOAP::Transport::MAILTO::Client)       [yes]
Client FTP support (SOAP::Transport::FTP::Client)                    [yes]
Standalone HTTP server (SOAP::Transport::HTTP::Daemon)               [yes]
Apache/mod_perl server (SOAP::Transport::HTTP::Apache, require Apache)[no]
FastCGI server (SOAP::Transport::HTTP::FCGI, require FastCGI)         [no]
POP3 server (SOAP::Transport::POP3::Server)                          [yes]
IO server (SOAP::Transport::IO::Server)                              [yes]
MQ transport support (SOAP::Transport::MQ)                            [no]
JABBER transport support (SOAP::Transport::JABBER)                    [no]
MIME messages [required for POP3, optional for HTTP] 
    (SOAP::MIMEParser)                                                [no]
SSL support for TCP transport (SOAP::Transport::TCP)                  [no]
Compression support for HTTP transport (SOAP::Transport::HTTP)        [no]

Do you want to proceed with this configuration? [yes]
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Web Services in Java with Apache SOAP
Creating web services in Java is more work than in Perl with SOAP::Lite, but the process is essentially the same. To illustrate how it's done, let's create the same Hello World web service and deploy it using the Apache SOAP tools.
Apache SOAP is the Apache Software Foundation's implementation of the SOAP protocol. It is designed to run as a servlet within any Java HTTP Server. As such, it implements only the proxy part of the message handling process. Like SOAP::Lite, Apache SOAP's list of features is impressive, sharing many of the same benefits as its Perl-based counterpart.
Apache SOAP can be used as both a client and provider of SOAP web services. A server-side installation of Apache SOAP involves placing some .jar files in your classpath. You will need a separate web server that supports Servlets and Java Server Pages, such as Apache's Tomcat (http://jakarta.apache.org/tomcat/).
The Apache SOAP homepage, http://xml.apache.org/soap/index.html, has links to both source-only and precompiled distributions of the toolkit. Installing the precompiled binary distribution is as simple as downloading a Zip archive and extracting it into a directory.
On the client, three .jar files from the distribution (soap.jar, mail.jar, and activation.jar) must be present in your classpath. Also present must be any Java API for XML Parsing (JAXP) aware XML parser, such as Xerces Version 1.4 (http://xml.apache.org/xerces-j/).
Assuming that you installed Apache SOAP .jar files in the C:\book\soap directory, set your SOAP_LIB environment variable to C:\book\soap\lib. Adding the .jar files to your classpath then entails:
set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\soap.jar
set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\mail.jar
set CLASSPATH = %CLASSPATH%;%SOAP_LIB%\activation.jar
Or, in the Unix Bourne shell (/bin/sh):
CLASSPATH = $CLASSPATH;$SOAP_LIB/soap.jar
CLASSPATH = $CLASSPATH;$SOAP_LIB/mail.jar
CLASSPATH = $CLASSPATH;$SOAP_LIB/activation.jar
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Web Services In .NET
For web service developers working strictly on the Windows platform, Microsoft's .NET development platform offers built-in support for easily creating and deploying SOAP web services. Let's walk through how you create the Hello World service using C#, the new Java-like programming language designed specifically for use with .NET.
The first thing you need to do is download and install the Microsoft .NET SDK Beta 2 from http://msdn.microsoft.com. This free distribution contains everything you need to create and run any .NET application, including .NET Web Services.
There are, however, several prerequisites that you need:
  1. You must be running Windows 2000, Windows NT 4.0, Windows 98, or Windows Millennium Edition.
  2. You must have Microsoft Internet Explorer Version 5.01 or higher.
  3. You must have the Microsoft Data Access Components (Version 2.6 or higher) installed.
  4. And you must have Microsoft Internet Information Server (IIS) installed and running. .NET Web services can only be deployed within the IIS environment.
The .NET Framework SDK installation is a fairly automatic process, with an easy-to-use installation wizard. Once installed, we can create the Hello World service.
Before we get into exactly how web services are created in .NET, let's take a quick walk through the .NET architecture to help put things into perspective.
First and foremost, .NET is a runtime environment similar to the Java Virtual Machine. Code packages, called assemblies , can be written in several .NET specific versions of popular programming languages like Visual Basic, C++, C#, Perl, Python, and so on. Assemblies run within a managed, hierarchically organized runtime called the "Common Language Runtime" that deals with all of the low-level memory and system management details (see Figure 3-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!
Interoperability Issues
At the time of this writing, .NET's SOAP implementation still has a few issues that need to be worked out, primarily in the area of interoperability.
Slight variations between the way .NET implements SOAP and SOAP::Lite's implementation of SOAP, for example, cause some difficulty in allowing the two to work together out of the box. To illustrate the problem, follow the steps shown here. One would think that everything would work fine, but it doesn't. I'll point out why after we walk through it.
First, launch the Java TcpTunnelGui tool that ships with Apache SOAP, specifying port 8080 as the local listening port, and redirecting to whatever server you have your HelloWorld.asmx file deployed to:
C:\book>start java org.apache.soap.util.net.TcpTunnelGui 8080
        localhost 80
Then, modify the Perl Hello World client to point to the HelloWorld.asmx file, but replace the server part of the URL with localhost:8080.
When you run the Perl script:
C:\book>perl hello_client1.pl James
The result is not what you would expect. The script ends without ever displaying the "Hello James" result. If you take a look at the TcpTunnelGui tool, you'll see that the SOAP message is sent, but the .NET runtime rejects the request and issues a SOAP fault in response. This is shown in Example 3-19.
Example 3-19. SOAP fault from .NET
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <soap:Fault>
      <faultcode>soap:Client</faultcode>
      <faultstring>
          System.Web.Services.Protocols.SoapException: Server did 
          not recognize the value of HTTP Header SOAPAction: 
          urn:Example#sayHello.
          at System.Web.Services.Protocols.SoapServerProtocol.Initialize(  )
          at  System.Web.Services.Protocols.ServerProtocolFactory.Create(
          Type type, HttpContext context, HttpRequest request, 
          HttpResponse response)
      </faultstring>
      <detail />
    </soap:Fault>
  </soap:Body>
</soap: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!
Chapter 4: The Publisher Web Service
The Publisher web service is a demonstration of a more complex web service modeled after the one used by the SOAP Web Services Resource Center (http://www.soap-wrc.com). This service demonstrates techniques for implementing more complicated forms of web services. It builds on the Hello World example from Chapter 3.
The Publisher web service manages a database of important news items, articles, and resources that relate to SOAP and web services in general.
A Perl-based service allows registered users to post, delete, or browse items, and to manage their registration information. We've also implemented an interactive Java shell client that uses the Apache SOAP client.
The supported operations are:
register
Create a new user account.
modify
Modify a user account.
login
Start a user session.
post
Post a new item to the database.
remove
Remove an item from the database.
browse
Browse the database by item type. The data can be returned in either a publisher-specific XML format or as a Rich Site Summary (RSS) channel.
Security in the Publisher service is handled through a login operation that returns an authorization token to the user. This token consists of a user ID, email address, login time, and a MD5 digest that the user must include in all operations that require that the user be authenticated, namely the post and remove operations (see Figure 4-1).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Overview
The Publisher web service manages a database of important news items, articles, and resources that relate to SOAP and web services in general.
A Perl-based service allows registered users to post, delete, or browse items, and to manage their registration information. We've also implemented an interactive Java shell client that uses the Apache SOAP client.
The supported operations are:
register
Create a new user account.
modify
Modify a user account.
login
Start a user session.
post
Post a new item to the database.
remove
Remove an item from the database.
browse
Browse the database by item type. The data can be returned in either a publisher-specific XML format or as a Rich Site Summary (RSS) channel.
Security in the Publisher service is handled through a login operation that returns an authorization token to the user. This token consists of a user ID, email address, login time, and a MD5 digest that the user must include in all operations that require that the user be authenticated, namely the post and remove operations (see Figure 4-1).
Figure 4-1: When registered users log in, they will be given an authentication token that they must use whenever they post or remove an item in the database
In the login operation, the user's ID and password are sent (in plain text) to the publisher service where they are validated. The service then creates an authentication token and returns it to the user. While not very secure, this illustrates one way that authentication can occur in SOAP-based web services. That is, rather than using transport-level security mechanisms, such as HTTP authentication, security can be built into the web services interface directly. In Chapter 5, we will discuss several much more secure and robust security mechanisms for web services.
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 Publisher Operations
The operations exposed by the Publisher service are fairly straightforward. If we cast these operations in a Java interface, they would look like Example 4-1.
Example 4-1. The Publisher interface in Java
public Interface Publisher {

  public boolean register (String email, 
                           String password, 
                           String firstName, 
                           String lastName, 
                           String title, 
                           String company, 
                           String url);

  public boolean modify   (String email,
                           String newemail,
                           String password,
                           String firstName,
                           String lastName,
                           String title,
                           String company,
                           String url);

  public AuthInfo login   {String id, 
                           String password);

  public int post         (AuthInfo authinfo,
                           String type,