Chapter 3. Understanding Web Services

CONTENTS

IN THIS CHAPTER

  •  What Is a Web Service?
  •  Crystal Ball Readings
  •  The ABCs of Web Services
  •  How to Use a Web Service
  •  Summary

The first revolution with the Internet was all about delivering information to people. We are now in the second revolution, which focuses on delivering information to systems. XML is the tool that makes this new revolution a reality, and Web services are the methods with which businesses will drive system-to-system communication.

This chapter will introduce the Web services concept and teach the basic facts behind both Web services and the various APIs that power it. The goal of the chapter is to introduce most of the major initiatives, standards, APIs, and toolsets that make up Web services. This will help reduce the confusion that arises when too many letters are strung together in meaningless names, a problem that plagues Web services. We will walk you through expanding the development environment that was set up in Chapter 1, "Integrating JSP and Data," to use Web services. Finally, the chapter will show some basic coding examples to get your feet wet with the Web services concept.

What Is a Web Service?

Let's start with the simplest definition. In the purest sense, a Web service is a product in the form of a reusable function built by one company that is exposed on the Internet for another company to use.

You can already find Web services on the Internet. A simple example is the automated site search service provided by Atomz. For a demonstration, use the search engine at www.jspinsider.com; the search request happens at the JSP Insider site, but the actual search occurs at another site hosting the search service. The Web service concept is growing and an exciting new model of business is evolving. What we now have is a situation where the Web service concept is exploding into new territory and expanding in its capabilities. The basic high-level goal of Web services is to further distributed computing (where application logic is separated into logical pieces and runs across many machines). The practical reason to build a Web service is to permit businesses to provide small, reusable, and self-describing computing methods to each other. A Web service by itself is just a piece of code that can be called by other applications or remote processes; however, if a programmer in the near future could pull together enough Web services, he or she could stitch together most of the features needed to support an entire Web application. The practical goal of a Web service is to permit a business to concentrate only on its core business needs and call up prepackaged "Web services" to complement the core business.

At the time of this writing, Web services are new enough that all of this is still not a reality. However, networks such as Microsoft's .NET Passport are being built on this Web services concept. As the Web services networks are built, we have the chance to watch as they are cobbled together into realistic systems. In many respects, this situation is very similar to when the Internet first began to open up to the commercial world in the 1990s.

The definition given at the beginning of this section applies to a Web service in the broadest sense of the term. The fact is that, at the beginning of 2002, there really wasn't a standard definition of a proper Web service. Every expert would give you a slightly different answer. For this book, a Web service is a remote Internet service that is capable of sending and receiving data over an HTTP network within a well-defined XML package. The difference between a Web site and a Web service is the use of XML to finely define and control the data being sent to and from a Web service. This brings up an interesting point: Unlike XML, which has the W3C to control and define XML, currently no single organization exists to define the nature of a Web service. Instead, a Web service is defined by the collection of tools and specifications a programmer uses to build it. What makes it all work is that nearly everyone is using the same set of standard specifications. Over time, this confusion will be resolved, and some large organization such as the United Nations (see the section titled "ebXML" later in this chapter) or W3C will take control of the larger Web services definition.

It is important to note that in this general discussion of Web services we are discussing both the creation of a Web service and the use of one. The creation of a Web service includes writing, exposing, and registering it for all authorized users to see and use. The use of a Web service includes finding and interfacing with the Web service in a stable, predictable manner.

At this point, it would be appropriate to define the terms client and server. A server is a computer or device that manages resources. According to this definition, a Web service server is any machine or device that responds to requests. This server manages resources by controlling the output of information through Web service responses. A client is any application that relies on a server to perform some operations. In this case, the Web service requestor is the client, as it is relying on the Web service server for information through responses.

Key features of creating and using Web services are listed here:

  • They are accessible using standard Internet protocols such as HTTP or SMTP.

  • They are distributed, which means that a Web service will usually reside on a different server than the applications that use the service.

  • They can be centralized to a single source. This means that you can code once and access many times from many projects. In other words, Web services allow increased code reuse.

  • A single Web service isn't a full application, but rather a standalone function that can be called by many different applications.

  • A Web service can be self-describing. This enables businesses and applications to find and use Web services through automated processes and Internet registries (an electronic yellow pages to let other programs find the service).

All of these features add up to make a Web service a reusable component that can broadcast its functionality across an Internet network.

The advantages of creating and using a Web service come from the distributed nature of the overall system. They include the following:

  • Logic can be broken into smaller reusable pieces of code.

  • The code can be used by many different applications. For example, a Web service written in ASP.NET can be accessed by a JSP page.

  • The code can be registered so that many different organizations can use a single Web service. As a result, the builder of a Web service doesn't need to communicate with every customer.

  • Web services can describe themselves to the world through special registries.

  • Standard protocols, APIs (standard code), and tools (coding development packages) are evolving to allow programmers to build and access Web services. In the future, these tools will allow for the automatic creation of a Web service. This will open the creation of Web services to developers of all skill levels, as they won't need to know the underlying mechanics.

The disadvantages of Web services include the following:

  • You will need to create another software tier to utilize Web services. This new layer means that you must give careful consideration to application and service architecture in systems that utilize a Web service.

  • Accessing Web services over the Internet causes both security and speed concerns for an application designer. However, you can increase the security of a Web service at the expense of speed.

  • Automated tools such as Microsoft's Visual Studio .NET or Sun's Forte that support Web services are currently young and few. This means that in order to successfully build a Web service, you must clearly understand an entire set of protocols and APIs.

  • Web services are new within the programming community. Solid and proven design patterns still need to be established for them. As a result, very few practical online resources exist to help a struggling programmer learn how to successfully implement a Web service.

As is often the case in the computer industry, it takes several iterations to get things right. In the case of Web services, this is especially true, as Web services are truly another iteration of older ideas. Their design aids in the reduction of development time and promotes code reuse.

Crystal Ball Readings

Web services are rapidly changing, and represent different things to different people. Because of this, it is important to give you an idea of what to expect in the future in order to place what you are learning in proper perspective. The goal is to show the probable direction of Web services. Of course, by the time you read this section, some of these predictions will have been realized or will no longer be possible, which means that you should take these predictions with a grain of salt.

So what can we expect for the future from Web services?

  • The year 2002 will be marked with as many failures as successes with regard to Web services. The failures will result from trying to replace more traditional business models with Web services. Successful Web service implementations will be systems that start small or integrate Web services into existing business practices. This means that most failures will be due to projects pushing the Web services paradigm too fast and too hard.

  • Web service implementation will become stabilized and by mid-2002 most J2EE servers will implement an easy front end to make using Web services more transparent.

  • Web service tools will be divided primarily between Microsoft's .NET Framework and Java J2EE implementations. Since Web services are product independent, this doesn't pose a problem. Developers will chose to build Web services using the tool that best matches their business needs.

  • Web service design structure will become more stable. By the end of 2002, the influence of successes and failures will establish practical business design guidelines for building successful Web services.

  • The initial market for Web services in 2002/2003 will be smaller than what the 2001 hype portrays. New technologies very rarely live up to the hype, and the slow economic realities of 2001 will only slow Web services.

  • Ironically, Web services will be most effectively used internally, providing a place to centralize and reuse business logic across many different Web applications for larger companies and state organizations. For some Java shops, this will be a method to avoid using EJBs. Enterprise JavaBeans are distributed Java objects (they are not JavaBeans, which are basically standalone Java objects). Most shops will tie EJBs and Web services closely together for their business. This in effect will create two different styles of Web service implementation for Java programmers: EJB-based Web services and JSP/Servlet/JavaBean-based Web services. The difference between the two styles will be a reflection of the framework being implemented by a project. Systems using J2EE systems will usually implement EJB-based Web services, while smaller projects based solely on JSP/servlets will use Web services based on JSP, servlet, and JavaBean technologies.

  • In 2003, Web services will begin to be included in Web application design. This means that Web services will be used not by early user pioneers, but by businesses.

  • The development of Web services can be highly automated and most Web service development will be through these automated tools. The first solid tools will be available in 2002. However, it won't be until 2004 that these tools will be fully mature and in widespread general use.

  • Many implementations of Web services will fail as programmers experiment with the boundaries of Web service design. This will be similar to the trend of implementing EJB designs when simpler designs would have been quicker, cheaper, and simpler to build.

  • Finally, expect that Web applications of the future will only use a handful of commercial Web services. The Web services market will be similar to the COM market for building Microsoft-based solutions. People will use public domain or commercial Web services to complement their applications for a few tasks, but the majority of programmers will build their own for specialized tasks.

These predictions are based on the authors' experiences with various technology implementations over the past 15 years. This isn't a scientific study of consumer need, but rather is based on similarities between Web services and other products.

All of this leads to the conclusion that, due to the slippery and constantly changing nature of Web services, the majority of programmers should not rush into using them. Instead, we suggest that you carefully and slowly enter into the Web services marketplace. Start with small implementations to gain experience. Once you've reached an understanding of Web services and the major tools have matured to the point at which they're acceptable for your business needs, jump in with both feet. Due to the small and distributed nature of a Web service, taking a slow and controlled approach is very practical.

This book has three chapters that pertain specifically to Web services:

  1. This chapter provides an introduction to the various APIs that a Web service might use in its implementation.

  2. Chapter 8, "Integrating JSP and Web Services," demonstrates how to implement Web services in a JSP-only environment. This book will not examine how to use Web services within a J2EE application server.

  3. Chapter 14, "Building a Web Service," will cover the basics needed to get you to a point at which you can implement a Web service that others can access through an UDDI registry. Web services should be simple enough to build and use without much fuss.

The ABCs of Web Services

While building a Web service might be simple, getting started is very confusing. There exists an entire universe of initiatives, products, and APIs to sort through. If as a new user you are confused by this alphabet soup muddle, don't despair; things are getting better and more concise in the Web services development arena. The best news is that as a developer, you will only have to know a few critical pieces to make things work.

As stated earlier, much of what it takes to build a Web service will be automated in the future. In addition, higher-level APIs that hide the complexity of Web service infrastructure are being developed. Your programming style will determine when you should consider building Web services. For programmers who want full control and need to know the entire picture, now is the time to dive in. If you are more of a business-level programmer (concentrating mainly on your business requirements), you can wait a few months for the tools to catch up so that you can concentrate mainly on the business logic rather than the lower-level details of Web services.

First, let's look at how things work when everything is in action. Figure 3.1 gives an overview.

Figure 3.1. Overview of a Web service.

graphics/03fig01.gif

Let's review the steps involved in using a Web service, as shown in Figure 3.1.

  1. A Web service provider registers a Web service. This can be done either manually or automatically through code.

  2. A user requests a Web page.

  3. The Web application accesses a Web service. If the service client already knows about the Web service, it directly accesses the Web service (step 3a). However, if the Web service cannot be found, the service client can query to discover/rediscover an appropriate Web service to use (step 3b). Once done, the client can re-query a Web service with the revised information.

  4. The Web service processes the request.

  5. The results of the execution of the Web service are sent back to the requesting client.

  6. The Web service results are incorporated into the final page.

  7. The client receives a Web page, not realizing that the application ever used a Web service.

The Basic Building Blocks

A Web service consists of several components. This section will review the components that make up an average Web service.

XML

Without XML, Web services would not have been possible. Virtually every aspect of a Web service uses XML in some manner. As an example, sending a message to invoke a Web service uses SOAP (Simple Object Access Protocol), which is entirely built on top of XML.

SOAP (Simple Object Access Protocol)

After XML, the second most important piece in the Web service puzzle is SOAP. This is a protocol for transferring queries and responses used by a Web service. Like the XML and HTML specifications, SOAP is maintained by the World Wide Web Consortium (W3C). The W3C's goal is to develop interoperable specifications and guidelines. The W3C defines SOAP as an XML-based protocol to exchange information in a decentralized and distributed environment.

SOAP has three parts:

  1. The first part is an envelope in which a message is contained. This envelope is important as it does more than just hold a message.

    The envelope also

    • Describes what is in the message (sounds like XML, doesn't it? Self-describing envelopes )

    • Contains rules on how to process the message

    • Includes information on which Web service should respond to the message

    • Contains information that indicates whether responding to the message is optional or mandatory

      The SOAP envelope gives quite a bit of information to the receiving Web service. With the data received, a Web service is able to determine whether it should process a SOAP service request or not.

  2. SOAP also has a set of encoding rules to define special Web service defined data types. This feature is helpful, as it allows the definition of unique data types for a service. Any data that can be described as an XML structure can be embedded and used within a SOAP message.

  3. SOAP includes rules for describing the exposed methods of a Web service. This includes a structure for the description of the calls and responses of a Web service.

SOAP allows a program to invoke a service through the interchange of messages. It permits entities to invoke each other's exposed methods regardless of the programming language or network used to build and host the entities. An entity is anything that invokes a SOAP call, such as an application, a Web service, or any program.

SOAP can use any combination of other protocols for transporting messages between Web services. However, HTTP (Hypertext Transfer Protocol) is the protocol of choice for delivering messages. HTTP is the underlying protocol used by the World Wide Web. It defines how messages are transmitted and formatted and what actions Web servers should take in response. HTTP is favored due to its widespread availability and its ability to navigate through obstacles such as firewalls.

A simple SOAP message might appear as in Listing 3.1.

Listing 3.1 A Simple SOAP Message
<SOAP:Envelope   xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"   SOAP:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">    <SOAP:Body>        <EXAMPLE:getBookPublisher xmlns:EXAMPLE="Example-URI">            <title>JSP and XML</title>        </EXAMPLE: getBookPublisher >    </SOAP:Body> </SOAP:Envelope>

In this example, the element <SOAP:Envelope> encloses the entire message, which is contained within the <SOAP:Body> element. Also note that in the envelope tag, the SOAP:encodingStyle attribute indicates the encoding specification of the message. That is, when a SOAP server validates this message, it can refer to the schema found at http://schemas.xmlsoap.org/soap/encoding/ to find the rules with which this message was encoded. For this example, we are accessing a fictitious Web service method called getBookPublisher. For this method, the example passes the value JSP and XML into the <title> element, which acts as a return parameter called title.

To complete this example, let's imagine that a Web service responded to the example message. A response might look like the one in Listing 3.2.

Listing 3.2 A SOAP Response Message
<SOAP:Envelope   xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"   SOAP:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/">    <SOAP:Body>        <EXAMPLE:getBookPublisherResponse xmlns:EXAMPLE="Example-URI">            <name>SAMS Publishing INC.</name>        </EXAMPLE:getBookPublisherResponse >    </SOAP:Body> </SOAP:Envelope>

The routing of the SOAP message is handled by another protocol. This example doesn't demonstrate the protocol with which the message is transported. As stated earlier, HTTP is the preferred protocol for transferring SOAP messages.

SOAP has clients and servers. A SOAP server is an application waiting to process requests from a SOAP client. The SOAP server will interpret incoming SOAP requests and convert them into a format that the receiving process can use. Any request that the server cannot process will be rejected. A SOAP client is any application or piece of code sending a SOAP message to be processed by the server.

Another important term within SOAP is RPC (Remote Procedure Calls). RPC is a method of writing the procedure calls and responses that are found in SOAP messages. RPC enables a client to invoke a procedure call on a server. The client program sends a message to the server with the appropriate arguments for the method being called. Then the server returns a message containing the results of the program executed. In essence, RPC is a format through which these procedure calls and responses must be made. While we could just use SOAP to send messages between applications and act on the messages, using SOAP RPC gives a well defined method of declaring parameters and methods to be accessed over a SOAP message.

To use SOAP, we will need a server or API that implements the SOAP protocol. The Java API section of this chapter will go into more detail on two common SOAP tool implementations.

Before concluding our discussion of SOAP, we need to discuss security. SOAP frequently uses text-based XML and HTTP. This effectively means that any message transported with SOAP is exposed for the world to view. Currently, two simple solutions exist to protect sensitive data placed within a SOAP envelope.

  1. Use SSL (Secure Sockets Layer) to transmit the messages back and forth. SSL is a protocol designed to transfer private documents over the Internet. The disadvantage of SSL relates to performance considerations. Simply put, security comes at the price of speed. Also, sometimes system architecture can have security ramifications for an SSL solution.

  2. Encrypt the data that is wrapped within the SOAP message. The disadvantage of this method is that a Web service must be expecting the encrypted data and therefore can only be used with specific Web services designed to use encryption.

An in-depth security discussion is beyond the scope of this chapter. However, you should consider the following piece of advice: If you need high security in your Web service transactions, the security needs to be addressed at the start of your project.

For more information on SOAP refer to the SOAP Web site at http://www.w3.org/TR/SOAP.

WSDL (Web Service Description Language)

WSDL is an XML-formatted language for describing Web services. WSDL is a standard maintained by the W3C, and was originally proposed by Ariba, IBM, and Microsoft. The strength of WSDL lies in its ability to describe a Web service in a standard way. While we can use SOAP to access and query a Web service, we still need a way to determine the capabilities of the Web service. WSDL performs this task. By querying a Web service registry, we can obtain the WSDL document stored there. Through this document, we can retrieve information regarding the Web service in question. It is this information that will allow the client to determine what methods to call, how to use them, and where to direct those requests.

The real meat of WSDL is the document definition of the standard XML document used to describe the Web service. So let's look at an example WSDL file and review the high points of the document. The example WSDL file used here will be from a Web service that we will access later in the chapter. The WSDL definition can be found at the XMethods Web site (http://www.xmethods.net/). This site has a simple registry that publishes a list of Web services. From this list, the service selected is called "TemperatureService" and is geared at getting the current temperature at a zip code. The WSDL document for this service appears in Listing 3.3.

Listing 3.3 XMethods TemperatureService WSDL File
<?xml version="1.0" ?> <definitions name="TemperatureService"            targetNamespace="http://www.xmethods.net/sd/TemperatureService.wsdl"            xmlns:tns="http://www.xmethods.net/sd/TemperatureService.wsdl"            xmlns:xsd="http://www.w3.org/2001/XMLSchema"            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"            xmlns="http://schemas.xmlsoap.org/wsdl/"> <message name="getTempRequest">        <part name="zipcode" type="xsd:string" /> </message> <message name="getTempResponse">      <part name="return" type="xsd:float" /> </message> <portType name="TemperaturePortType">      <operation name="getTemp">               <input message="tns:getTempRequest" />               <output message="tns:getTempResponse" />      </operation> </portType> <binding name="TemperatureBinding" type="tns:TemperaturePortType">   <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />   <operation name="getTemp">      <soap:operation soapAction="" />      <input>        <soap:body use="encoded" namespace="urn:xmethods-Temperature"                   encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />      </input>      <output>        <soap:body use="encoded" namespace="urn:xmethods-Temperature"                   encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />      </output>   </operation> </binding> <service name="TemperatureService">      <documentation>Returns current temperature in a given U.S. zip code      </documentation>      <port name="TemperaturePort" binding="tns:TemperatureBinding">         <soap:address          location="http://services.xmethods.net:80/soap/servlet/rpcrouter" />      </port> </service> </definitions>

Now let's walk through this XML document to highlight the various sections of a WSDL service document. This discussion is just a brief introduction to a few critical elements needed to translate the information from a WSDL document for use in a Web service invocation.

The initial high-level definition of the Web service is placed within the service element:

<service name="TemperatureService">

The document subelement gives us a description of the service:

<documentation>Returns current temperature in a given U.S. zipcode </documentation>

The port subelement defines where the service resides. Each port will have a unique name and binding attribute. The binding attribute must match to a previous binding element:

<port name="TemperaturePort" binding="tns:TemperatureBinding">

The location attribute gives us the URL to access this service:

         <soap:address          location="http://services.xmethods.net:80/soap/servlet/rpcrouter" />      </port> </service>

Next, we need a way to specify the messages being sent around. The binding element defines the SOAP message format, protocols (SMTP, HTTP, and so on), messages the service will use (typically a request and response). The soap:binding subelement binds a SOAP envelope format to match to the Web service. Since we are using SOAP, the soap:binding element is a required element. To summarize, the binding takes the abstract information required for the calls to and from the Web service and produces a real physical model of the messages to be sent to and from the service.

Here's how the binding element works:

<binding name="TemperatureBinding" type="tns:TemperaturePortType">

The transport attribute indicates the protocol to use, in this case HTTP:

<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />

An operation matches to each method the Web service exposes for use:

<operation name="getTemp">

The soapAction is an HTTP header the client sends when invoking the service:

<soap:operation soapAction="" />

The message the Web service expects to receive to initiate this method is defined within the input element:

<input>

The namespace is a unique URI used to reference the service method:

  <soap:body use="encoded" namespace="urn:xmethods-Temperature"              encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </input>

The message the Web service sends back out from this method is defined within the output element:

   <output>      <soap:body use="encoded" namespace="urn:xmethods-Temperature"                   encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />    </output>     </operation> </binding>

Now let's look at how WSDL defines what methods are available from a Web service. The portType element defines a collection of all methods that the Web service exposes to the world. (Each operation matches a method.) In relation to SOAP, all operations have an input and output message that needs to be defined for use. Finally, the binding element shown previously will further define the operations first referenced in portType:

<portType name="TemperaturePortType">        <operation name="getTemp">                 <input message="tns:getTempRequest" />                 <output message="tns:getTempResponse" />        </operation> </portType>

The final piece to examine is how to define the parameters being sent back and forth within the messages. The message element, shown in the following code, defines the parameters that must be embedded within a message. For us, this translates to the method arguments and return values.

The first thing to notice is that the name matches a message attribute defined with the portType:

<message name="getTempRequest">

This message has a parameter called zipcode of type string:

         <part name="zipcode" type="xsd:string" /> </message>

This message also returns a value of type float:

<message name="getTempResponse">        <part name="return" type="xsd:float" /> </message>

The key to learning and understanding WSDL is just working through the WSDL document specification. For more information, you can refer to the WSDL Web site at http://www.w3.org/TR/wsdl.

Service Management Initiatives

Once you've built a Web service, oftentimes you also want a way to let others know about it. This section will review the current options for listing a Web service for public access.

UDDI

Universal Description, Discovery, and Integration (UDDI) is a distributed directory that allows businesses to list themselves on the Internet. This directory is found on the Web, and, like the white and yellow pages of a phone book, enables businesses to find each other.

UDDI was started by Ariba, IBM, and Microsoft. The UDDI framework defines what Web-based services a business offers and creates a global registry specifically geared towards business-to-business electronic commerce. The core of the UDDI business registration is an XML file describing a business and any Web service it might provide. UDDI acts as an electronic phone book that provides information in three sections:

  • Green pages The green pages provide technical data about a business's services. The information found in the green pages includes pointers to technical information and URLs with more information about each service. It is interesting to point out here that while UDDI is advertised as primarily registering Web services, the actual index will permit any type of service to be indexed in the registry.

  • White pages The white pages consist of addresses and other contact data for business registrations. This is the basic identification information for a business registering to provide services.

  • Yellow pages The yellow pages are sorted by industrial categorizations to make searching for a business easier. The categories are based on several standard business coding systems such as SIC (Standard Industrial Classification) and the NAICS (North American Industry Classification System).

The overall UDDI registry is hosted across many sites. Currently both IBM and Microsoft are hosting UDDI registries. Information from each of these registries is duplicated so when you register at one site your business information is replicated across the entire UDDI registry.

Businesses can access UDDI either through a Web interface or through automated programming methods. Any company using the registry can have automated methods to query and find an appropriate service for their customers. In addition, your own services can automatically update themselves within the registry, so the UDDI registry always reflects current information.

It should be noted that UDDI by itself only provides basic searching features. More advanced features such as searching by price of service or geographic region are not part of the UDDI framework. Instead, UDDI permits others to add a new layer on top of the current framework to provide such features. In the future, various third parties will create search engines for querying the UDDI registry for the general business community. This evolution will end up having similarities to the current search engine marketplace for indexing Web sites.

From a technical point of view, the UDDI APIs are built on top of SOAP. A programmer can use the information supplied by the UDDI registry to directly query a Web service. The UDDI APIs are broken into two major sections. The first set is the Inquiry APIs. These are used to query the UDDI registry. The second set is the Publish APIs for creating and updating a UDDI registry entry.

The UDDI is not currently a standard. However, there are plans to submit UDDI to become a standard sometime in 2002. Currently UDDI is managed by dozens of companies.

For more information, you can refer to the UDDI Web site at http://www.uddi.org.

ebXML

ebXML (e-business XML) is a specification for standardizing XML globally to aid in trade between organizations of any size. It provides a standard method to exchange business messages written in XML.

This is a huge project that has many subgoals and groups working towards promoting electronic business. ebXML will become a formal standard using XML to provide a framework for messages and services for businesses and consumers.

The ebXML project is noteworthy because it is backed by the United Nations (UN). This project seeks to encourage enterprises around the world to conduct business with each other. More importantly, the goal is to create a single global electronic marketplace where anyone can engage in business. The other organization behind ebXML is OASIS. This organization consists of over 170 members, including many of the large technology companies. The primary goal of OASIS is to promote standards in XML to improve electronic business. Between the UN and OASIS, ebXML has the backing to become a rock solid specification. ebXML will bring with it a set of tools, APIs, and registries to empower businesses to exchange information with each other.

At the time of this writing, ebXML is new enough that it doesn't impact the way we currently build Web services. It isn't practical to cover an example of ebXML yet; it is just too new. The question then becomes When will ebXML become mature enough that ebXML standards will be used by our Web services? The answer to this is unclear; however, you needn't reexamine ebXML until late 2002 at the earliest.

For more information you can refer to the ebXML Web site at http://www.ebxml.org/geninfo.htm.

The Difference Between UDDI and ebXML

At first glance, UDDI and ebXML appear to be doing the same thing. However, while there is an overlap between the two initiatives, there is a difference between market focus and scope. ebXML is a much larger system aimed at general business-to- business communication. ebXML is designed to be a complete business-to-business solution while UDDI focuses on serving as a simple index and a place for companies to integrate Web services relative to each other.

Why do we need different service registries? The simple fact is that the marketplace will perceive a need for many different types of registries. From a technical point of view, ebXML is flexible enough with its structure to support most businesses, and this will reduce the need for more registries to appear in the marketplace. However, due to human nature and the mechanics of business, we can expect more registries to appear and disappear over time. Organizations will want their own system or someone will see a way to profit in making a new system. UDDI and ebXML are here to stay. Only time will tell what other registries will appear.

Finally, it should be noted that both ebXML and UDDI are supported by many of the same industries. This means that, over time, these two initiatives will end up complementing each other rather than competing with each other.

Java APIs

To make our lives easier, several Java applications and quite a few Java APIs exist to help us implement Web services. This section will discuss several of these projects.

Apache SOAP

http://xml.apache.org/soap

The Apache SOAP API is probably the most widely used Java SOAP implementation. Apache SOAP was built on top of the IBM SOAP4J API library. IBM donated the library to get a solid open source based SOAP implementation out for the development community. The code examples in this book use Apache SOAP.

AXIS

http://xml.apache.org/axis

AXIS is the next generation of a Java-based SOAP implementation (at the time of this writing, it is in the alpha stage). AXIS replaces the Apache SOAP API. AXIS is much faster than Apache SOAP due to design considerations such as using XML tools like SAX over DOM (we will cover SAX and DOM in future chapters). The drawback of AXIS is that the API is still in alpha release and as such is still too young to use in production environments.

JAXM (Java API for XML Messaging)

http://java.sun.com/xml/jaxm/index.html

JAXM implements SOAP 1.1. A programmer can use JAXM to enable a JSP page or Java object to send SOAP messaging. JAXM hides much of the lower level programming so a programmer can concentrate on sending a message. Eventually, JAXM will expand the messaging capabilities so that it offers functionality that SOAP cannot provide.

JAXM is listed as JSR-67 at the Java Community Process Web site. The Java Community Process is a community-based approach Sun takes to expand and improve upon Java. Whenever a new tool or feature for Java is required, a small team of programmers and companies is formed to oversee and develop the specifications and code.

JAXR (Java API for XML Registries)

http://java.sun.com/xml/jaxr/index.html

This API will be a valuable one for many programmers. The JAXR API will define a standard Java interface to access any Web service registry whether it is based on ebXML, UDDI, or another standard. It is important to understand that this API doesn't define a registry, but rather is purely a one-stop shopping interface to access any registry. While at the time of writing it was too early to use it, sometime in 2002 this API will be ready for prime time. The API currently uses ebXML to establish a baseline of required functionality; however, it is being expanded as needed for additional functionality. Currently, it supports only ebXML and UDDI specifications (version 0.6 at the time of writing). JAXR will use JAXM to communicate between the registry and a client.

JAXR is listed as JSR-093 at the Java Community Process Web site.

JWSDL (Java API for WSDL)

This API is designed to simplify using WSDL. JWSDL can represent and manipulate a service described by a WSDL document. Currently, JAXP is the best way to access and use a WSDL document. However, later in 2002, when JWSDL has become an established Java API, it will be the quickest and easiest API to use for WSDL documents. This API is really meant more for the tool builders programmers building the tools to access and use Web services. The average Web developer building a Web service will never need to access this API.

JWSDL is listed as JSR-110 at the Java Community Process Web site. At the time of this writing, no reference implementation of JWSDL has been released to the public.

How to Use a Web Service

Now that we have introduced Web services, let's play around and use one. To make life easy, let's go about this in a step-by-step process. These steps will be broken up between two sections.

  1. "Using SOAP" The first example is all about getting SOAP installed on our machines. We will set up a SOAP server to work alongside the Tomcat JSP Web server. We're using the SOAP server component of the Apache SOAP 2.2 Java API. Once we have this server up, we will build a very simple Web service to run on the local machine.

  2. "Roaming the Internet" The second example will show how to call up a Web service that isn't on the local machine.

Using SOAP

SOAP is really the core of Web services. In these examples, HTTP is the communication tier and Apache SOAP is the application handling the messages. We will use SOAP in two ways: firstly as a SOAP server to listen and process SOAP requests and secondly as a SOAP client to make requests. While many projects will only need to have a SOAP client, we will use both a client and a server to illustrate the full workings of SOAP.

Step 1: Installing a SOAP Server and Client

We need access to a Java implementation of SOAP. For this book, we will use the Apache SOAP API version 2.2. This software is open source and can be freely downloaded from http://xml.apache.org/soap/index.html. In this book we are using a nightly build of the SOAP application. The nightly builds can be found at http://xml.apache.org/dist/soap/nightly/. The nightly build has a few security features that are not found in the main 2.2 release. We recommend using either a recent nightly build or SOAP 2.3 when it is released in 2002.

Apache SOAP requires the following tools:

  • An XML Parser We are using Xerces, which is currently included with the Tomcat server.

  • JAF (JavaBeans Activation Framework) Simply defined, JAF is a framework for handling the transfer and use of data. Since SOAP is all about moving data back and forth, it makes logical sense that Apache SOAP would use JAF to simplify the internal coding. Sun defines JAF as "a set of standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and to instantiate the appropriate bean to perform said operation(s)." Fortunately, we really don't have to know anything about how to use JAF ourselves as it's used behind the scenes by Apache SOAP.

    JAF can be found at http://java.sun.com/products/javabeans/glasgow/jaf.html.

    To install JAF, all that you need to do is place activation.jar within your system's classpath so the Java Virtual Machine can find the JAF classes.

  • JavaMail JavaMail is a high-level Java API used to simplify the coding of e-mail applications. JavaMail is used by Apache SOAP to enable SMTP as a transport mechanism for SOAP messages.

    The JavaMail APIs can be found at http://java.sun.com/products/javamail/index.html.

    To install JavaMail, place the mail.jar within your system's classpath.

Once we have these tools, we are ready to install Apache SOAP. To use SOAP, we need to set up the SOAP client. This is required to permit our JSP container to reach out and talk to SOAP servers. To do this, Tomcat will need access to the soap.jar file that comes along with Apache SOAP. Place the soap.jar file into your classpath. Besides writing the code for the client request, this is the only step required for installing a SOAP client.

For this book, we placed the activation.jar, mail.jar, and soap.jar all in the Tomcat lib directory.

We also need a SOAP server to be up and running to process Web service requests. Within the Apache SOAP installation, you will find a soap.war file. Place this WAR file into your Tomcat webapps directory. This WAR contains a simple but complete Web application that functions as a SOAP server.

In the interest of conserving space, we won't repeat the general installation and testing examples that come with Apache SOAP. However, instead of installing SOAP at the root classpath level, we are having SOAP work through Tomcat. This will work for the examples in this book since we are going to use Tomcat and JSP for all the SOAP access (this is a JSP and XML book, after all). This means that all we really need to do is place the soap.jar, activation.jar, and mail.jar files into the Tomcat lib directory and install the soap.war file in order to have Apache SOAP run through Tomcat. One disadvantage of doing this, of course, is that you will not be able to run the SOAP examples from the Java command line. However, this will make setting up your classpath simple.

Once these files are in place, stop Tomcat and then restart it. Tomcat will install the SOAP server for you.

Let's write a quick test file, shown in Listing 3.4. (Save this file as webapps\xmlbook\chapter3\ShowClients.jsp.)

Listing 3.4 ShowClients.jsp
<%@page contentType="text/html"         import="java.net.*,                 org.apache.soap.server.*" %> <html> <head><title>List Current Clients</title></head> <body> Listing Current Clients on Local Server:<br/> <%     URL l_url = new URL ("http://localhost:8080/soap/servlet/rpcrouter");     ServiceManagerClient l_soap_client = new ServiceManagerClient(l_url);     String l_test[] = l_soap_client.list();     for (int i=0; i < l_test.length; i++)     {  out.print(l_test[i] + "<br/>"); } %> </body> </html>

This file replaces the command-line client test that is in the Apache SOAP documentation. That example validates the services that are running on the server. It works by creating a ServiceManagerClient object with which we can query a SOAP server. In our case, we are using this object to query the status of our local SOAP server. In this example, it queries the URL http://localhost:8080/soap/servlet/rpcrouter.

If you have just installed the SOAP server, this page will only return an empty listing. After all, we haven't installed any Web services yet. We need to build a Web service so we can have something to test.

Step 2: Building a Simple Service

You will be amazed at how simple this will be. The first thing we need to do is create a JavaBean. After all, from our viewpoint a Web service is just a Java object (JavaBean) with a fancy front end (Apache SOAP server). This means we will create the Web service under the SOAP Web application we installed in the previous step. In our case, the JavaBean will look like Listing 3.5. (Save this file as webapps\soap\WEB-INF\classes\xmlbook\chapter3\firstservice.java.)

Listing 3.5 firstservice.java
package xmlbook.chapter3; import java.beans.*; public class firstservice extends Object implements java.io.Serializable {   public firstservice() {}     public String testService ()     { return("First Test Service");} }

The Web service is called firstservice and it has one method called testService. The only thing this service does is return a string. Not very exciting, but we intentionally kept it simple so we can test everything quickly. Let's compile the Java file and move on to creating the SOAP deployment descriptor. (After compiling, stop and restart Tomcat so the firstservice.class file is registered within the SOAP server classpath.)

Once we have a Java object to use as a service, we must register the object with the SOAP server. Apache SOAP server uses an XML file called DeploymentDescriptor.xml to track the information of a Web service. The SOAP deployment descriptor is just an initialization file containing the basic service information. Let's go ahead and create this file. It turns out that the Apache SOAP server has a tool that permits us to type in the information and Apache SOAP automatically creates the deployment descriptor file. Point your browser to http://localhost:8080/soap/admin/index.html.

Select the Deploy service option. This will bring up an empty data entry screen. For our example, we can fill it in as shown in Figure 3.2.

Figure 3.2. Deploying a Web service on Apache SOAP server.

graphics/03fig02.gif

Note that this screen extends on for a bit, but for this example, we only need to enter the information shown in the screenshot.

Click the Deploy button at the bottom of the data entry frame (not to be confused with the Deploy button on the sidebar!) when you are done.

To prove that everything is working so far, let's run the first test file, ShowClients.jsp. As shown in Figure 3.3, this will demonstrate that our new service is indeed up and running and that it's available for access from outside the SOAP server.

Figure 3.3. Running ShowClients.jsp.

graphics/03fig03.gif

Step 3: Using a Service

Now that we have a service, the next trick is to show how to invoke the Web service. We are going to write a client to access the service. To write this client we need to do the following:

  • Gather up the information about the Web service in question. We need the name, parameters, and various other details about the service to track it down.

  • Invoke the service.

  • Extract any response sent back from the service.

For our current Web service, the detailed information we need to know is listed here:

  • The Target Service URI (urn:xmlbook.chapter3)

  • The method to invoke (testService)

  • Any parameters to pass in to the method (there aren't any, since our first service doesn't have any parameters)

  • The URL of the SOAP server in question (for us it's http://localhost:8080/soap/servlet/rpcrouter)

Now back in our XML book Web site it's time to add in the client JSP page shown in Listing 3.6. (Save this file as webapps\xmlbook\chapter3\RunFirstService.jsp.)

Listing 3.6 RunFirstService.jsp
<%@page contentType="text/html"         import="java.net.*,                 org.apache.soap.*,                 org.apache.soap.rpc.*" %> <%     String ls_result = "";     Call call = new Call ();     call.setTargetObjectURI("urn:xmlbook.chapter3");     call.setMethodName ("testService");     call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);     URL url = new URL ("http://localhost:8080/soap/servlet/rpcrouter");     Response resp = call.invoke (url, "");     if (resp.generatedFault())     {   Fault fault=resp.getFault();         ls_result = " Fault code: " + fault.getFaultCode();         ls_result = " Fault Description: " +fault.getFaultString();     }     else     {   Parameter result = resp.getReturnValue();         ls_result = (String) result.getValue();     } %> <html><head><title>Running a Local Web Service</title></head> <body> The result of the Web service call is <br/> <%= ls_result %> </body> </html>

In this example, the JSP page is acting as the client. When it is executed, it can successfully invoke firstservice, the service we created in a previous example. The result will look like Figure 3.4.

Figure 3.4. Running RunFirstService.jsp.

graphics/03fig04.gif

Now it's time to figure out what is happening. To do this, let's review the important sections of the RunFirstService.jsp example.

In the first section, the code of interest is the import statement. The classes of java.net.* are required for access to the URL object. The org.apache.soap classes were imported to access the Apache SOAP client APIs.

<%@page contentType="text/html"         import="java.net.*,                 org.apache.soap.*,                 org.apache.soap.rpc.*" %> <%     String ls_result = "";

Next, we use the Call object within Apache SOAP to access a Web service. The Call object represents the actual RPC call that is occurring. I personally think of it as my SOAP client because it's the object that is used to call the Web service. In fact, the Call object is the representation of the message to be sent to a Web service:

Call call = new Call ();

Once we have the Call object we need to initialize it with the Web service data (the identification data we supplied when creating the Web service on our SOAP server). The interesting thing to note here is that we are using Constants.NS_URI_SOAP_ENC to tell Apache SOAP to use the standard SOAP encoding. Most of the time, this will be the encoding value you will need to use. The URL object is storing the address of the SOAP server to access for the service:

call.setTargetObjectURI("urn:xmlbook.chapter3"); call.setMethodName ("testService"); call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC); URL url = new URL ("http://localhost:8080/soap/servlet/rpcrouter");

Once we have created our message (the Call object), the next step is to send the message. This is also known as invoking the service and we use the invoke method. The invoke method is a client-side only call to send a message to a service. The results of the call are placed in a Response object. The Response object represents the message sent back from an RPC call:

Response resp = call.invoke (url, "");

Once we have the Response object, we need to check the return message to see what has happened. First, we check for any errors. If something went wrong, we will query the response for the details of the error:

if (resp.generatedFault())  {   Fault fault=resp.getFault();      ls_result = " Fault code: " + fault.getFaultCode();      ls_result = " Fault Description: " +fault.getFaultString(); }

If everything is fine, we read the return value embedded within the message. In our case, we know that the Web service is only returning a String object, so we immediately type the return object to a String. In some cases, the logic to parse out the return value would be more robust to handle a complicated object or multiple values:

else {   Parameter result = resp.getReturnValue();     ls_result = (String) result.getValue(); }

The rest of the page is just an HTML document to display the results.

The code to access the Web service is relatively simple. Half the battle is getting the information of the Web service to call. The other half Apache SOAP takes care of for us in the sending and receiving of the message. All we are doing is creating a message object, receiving a message object, and querying the results.

Roaming the Internet

This section concentrates on using a remote Web service; we will build an example to access a publicly available Web service from the XMethods Web site. For a Web service, this example will use the TemperatureService service shown in Listing 3.3.

Choosing a Web Service

This example needs the parameters to call the service and that means it's time to go back to Listing 3.3 and the WSDL file. From this file, it is possible to get the information we need to access the Web service. The pieces of data we need are

  • The Target Service URI This is read from the namespace attribute of the soap:operation element. For this example, it works out to be urn:xmethods-Temperature.

  • The Web service method being invoked by our program This information is based on the operation element. For this service, we are using getTemp.

  • Any parameters needed for the Web service to run successfully These were stored in the message element. From this we find <part name="zipcode" type="xsd:string" />.

    This translates into one input parameter called zipcode of type String.

  • The URL of the SOAP server in question For us it's stored in the soap:address element, within the location attribute, which gets us a value of http://services.xmethods.net:80/soap/servlet/rpcrouter.

Using these values, we can now write a quick JSP page to access this Web service. The code is shown in Listing 3.7. (Save this file as webapps\xmlbook\chapter3\AccessService.jsp.)

Listing 3.7 Accessing the XMethods TemperatureService Web Service
<%@page contentType="text/html"         import="java.net.*,                 java.util.*,                 org.apache.soap.*,                 org.apache.soap.rpc.*" %> <% String ls_result  = "";    String ls_zipcode = (String) request.getParameter("zip"); if (ls_zipcode == null || ls_zipcode.length() == 0 || ls_zipcode.length() > 5) { ls_zipcode = "07931";}    Call call = new Call ();    call.setTargetObjectURI("urn:xmethods-Temperature");    call.setMethodName ("getTemp");    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);    /* Create the parameters to pass to the Web service */    Vector params = new Vector ();    params.addElement (new Parameter("zipcode", String.class,ls_zipcode, null));    call.setParams (params);   URL url = new URL ("http://services.xmethods.net:80/soap/servlet/rpcrouter");   Response resp = call.invoke (url, "");    if (resp.generatedFault())    {   Fault fault=resp.getFault();        ls_result = " Fault code: " + fault.getFaultCode();        ls_result = " Fault Description: " +fault.getFaultString();    }    else    {   Parameter result = resp.getReturnValue();        ls_result  = result.getValue().toString();    } %> <html> <head><title>Accessing a Remote Service</title></head> <body> The result of the Web service call is <br/> The temperature at <%= ls_zipcode %> is currently: <%= ls_result %> <form  method="post" action="AccessService.jsp">     <input type="text" name="zip" id="zip" value="<%= ls_zipcode %>" />     <input type="submit" value="Enter New Zip Code" /> </form> </body> </html>

When this JSP page is accessed, it will produce a page that looks like Figure 3.5.

Figure 3.5. Running AccessService.jsp.

graphics/03fig05.gif

Let's review the example. Most of the code in this example is identical to the RunFirstService.jsp example. The only difference is that this remote Web service is using parameters and our first example didn't need any parameters (because the service didn't use any). This shows that from a programming viewpoint the location of the Web service (local versus Internet) doesn't make much of a difference. From a practical viewpoint, running a remote service might incur additional overhead depending on the location of the Web service. However, those are design issues we will examine in a later chapter.

Let's look at the differences in the code.

While the JSP page is a little more complicated in that we use an HTML form on it (to submit a zip code back to ourselves), we only want to focus on the Web service differences. The only difference from a Web service point of view is the addition of parameters.

Usually, to use parameters we need to use a Vector object to place the parameter arguments:

Vector params = new Vector ();

Once we have the Vector, we place the arguments into our local copy of the Vector object:

params.addElement (new Parameter("zipcode", String.class,ls_zipcode, null));

Once we've finished adding parameters to the Vector, we append the Vector to the Call object.

call.setParams (params);

Everything else is as before we invoke our Call object and receive a response.

Calling a service isn't especially hard all the pain is in setting the service up and getting the tools together.

Summary

In this chapter, we reviewed the basics of Web services. As we saw, the larger picture is confusing, as many standards and software implementations exist. Ironically, despite the confusion within the marketplace, the process of building and using a Web service is simple. While Web services and the surrounding tools are still very young, it is a very promising technology for the future.

In future chapters, we will delve into details of implementing a JSP-based Web service. At the JSP Insider Web site (http://www.jspinsider.com), we have a bimonthly newsletter called the JSPBuzz. This newsletter is created with a combination of XML and JSP. We will use the data and examples from the JSPBuzz newsletter as a real-world example of using JSP and XML together. More importantly, we will apply Web services to the JSPBuzz to expose it to the world. We will show how the JSP Insider is building remote services that you can use to access the information stored in the JSPBuzz newsletter.

We've finished the last of the introductory chapters. These first three chapters were a concise review of the information needed to give newer programmers a basic level of understanding of JSP and XML. Now we are ready to dig into the meat of JSP and XML. The next chapter starts the fun part learning how to practically combine JSP and XML in your everyday projects.

CONTENTS


JSP and XML[c] Integrating XML and Web Services in Your JSP Application
JSP and XML[c] Integrating XML and Web Services in Your JSP Application
ISBN: 672323540
EAN: N/A
Year: 2005
Pages: 26

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net