Home > Articles > Web Development

  • Print
  • + Share This

Inventory Check Web Service

SkatesTown's inventory check Web service is very simple. The interaction model is that of an RPC. There are two input parameters: the product SKU (a string) and the quantity desired (an integer). The result is a simple boolean value—true if more than the desired quantity of the product are in stock and false otherwise.

Choosing a Web Service Engine

Al Rosen decided to host all of SkatesTown's Web services on the Apache Axis Web service engine for a number of reasons:

  • The open-source implementation guaranteed that SkatesTown will not experience vendor lock-in in the future. Further, if any serious problems were discovered, you could always look at the code to see what is going on.

  • Axis is one of the best Java-based Web services engines. It is better architected and much faster than its Apache SOAP predecessor. The core Axis team includes some of the great Web service gurus from companies such as HP, IBM, and Macromedia.

  • Axis is also probably the most extensible Web service engine. It can be tuned to support new versions of SOAP as well as the many types of extensions for which current versions of SOAP allow.

  • Axis can run on top of a simple servlet engine or a full-blown J2EE application server. SkatesTown could keep its current J2EE application server without having to switch.

This combination of factors leads to an easy sell. SkatesTown's CTO agreed to have all Web services developed on top of Axis. Al spent some time on http://xml.apache.org/axis learning more about the technology and its capabilities. He learned how to install Axis on top of SkatesTown's J2EE server by reading the Axis installation instructions.

Service Provider View

To expose the Web service, Al Rosen had to do two things: implement the service backend and deploy it into the Web service engine.

Building the backend for the inventory check Web service was simple because the logic was already available in SkatesTown's JSP pages (see Listing 3.3).

Listing 3.3  Inventory Check Web Service Implementation

import org.apache.axis.MessageContext;
import bws.BookUtil;
import com.skatestown.data.Product;
import com.skatestown.backend.ProductDB;

 * Inventory check Web service
public class InventoryCheck
     * Checks inventory availability given a product SKU and
     * a desired product quantity.
     * @param msgContext    This is the Axis message processing context
     *                      BookUtil needs this to extract deployment
     *                      information to load the product database.
     * @param sku           product SKU
     * @param quantity      quantity desired
     * @return              true|false based on product availability
     * @exception Exception most likely a problem accessing the DB
    public static boolean doCheck(MessageContext msgContext,
                                  String sku, int quantity)
    throws Exception
        ProductDB db = BookUtil.getProductDB(msgContext);
        Product prod = db.getBySKU(sku);
        return (prod != null && prod.getNumInStock() >= quantity);

One Axis-specific feature of the implementation is that the first argument to the doCheck() method is an Axis message context object. You need the Axis context so that you can get to the product database using the BookUtil class. From inside the Axis message context, you can get access to the servlet context of the example Web application. (Axis details such as message context are covered in Chapter 4, "Creating Web Services.") Then you can use this context to load the product database from resources/products.xml. Note that this parameter will not be "visible" to the requestor of a Web service. It is something Axis will provide you with if it notices it (using Java reflection) to be the first parameter in your method. The message context parameter would not be necessary in a real-world situation where the product database would most likely be obtained via JNDI.

Deploying the Web service into Axis is trivial because Axis has the concept of a Java Web Service (JWS) file. A JWS file is a Java file stored with the .jws extension somewhere in_ the externally accessible Web applications directory structure (anywhere other than under /WEB-INF). JWSs are to Web services somewhat as JSPs are to servlets. When a request is made to a JWS file, Axis will automatically compile the file and invoke the Web service it provides. This is a great convenience for development and maintenance.

In this case, the code from Listing 3.3 is stored as /ch3/ex2/InventoryCheck.jws. This automatically makes the Web service available at the application URL appRoot/ch3/ex2/InventoryCheck.jws. For the example application deployed on top of Tomcat, this URL is http://localhost:8080/bws/ch3/ex2/InventoryCheck.jws.

Service Requestor View

Because SOAP is language and platform neutral, the inventory check Web service can be accessed from any programming environment that is Web services enabled. There are two different ways to access Web services, depending on whether service descriptions are available. Service descriptions use the Web Services Description Language (WSDL) to specify in detail information about Web services such as the type of data they require, the type of data they produce, where they are located, and so on. WSDL is to Web services what IDL is to COM and CORBA and what Java reflection is to Java classes. Web services that have WSDL descriptions can be accessed in the simplest possible manner. Chapter 6, "Describing Web Services," introduces WSDL, its capabilities, and the tools that use WSDL to make Web service development and usage simpler and easier. In this chapter, we will have to do without WSDL.

Listing 3.4 shows the prototypical model for building Web service clients in the absence of a formal service description. The basic class structure is simple:

  • A private member stores the URL where the service can be accessed. Of course, this property can have optional getter/setter methods.

  • A simple constructor sets the target URL for the service. If the URL is well known, it can be set in a default constructor.

  • There is one method for every operation exposed by the Web service. The method signature is exactly the same as the signature of the Web service operation.

Listing 3.4  Inventory Check Web Service Client

package ch3.ex2;

import org.apache.axis.client.ServiceClient;

 * Inventory check web service client
public class InventoryCheckClient
     * Service URL
    private String url;
     * Point a client at a given service URL
    public InventoryCheckClient(String targetUrl)
        url = targetUrl;
     * Invoke the inventory check web service
    public boolean doCheck(String sku, int quantity) throws Exception
        ServiceClient call = new ServiceClient(url);
        Boolean result = (Boolean) call.invoke(
            new Object[] { sku, new Integer(quantity) } );
        return result.booleanValue();

This approach for building Web service clients by hand insulates developers from the details of XML, the SOAP message format and protocol, and the APIs for invoking Web services using some particular client library. For example, users of InventoryCheckClient will never know that you have implemented the class using Axis. This is a good thing.

Chapter 4 will go into the details of the Axis API. Here we'll briefly look at what needs to happen to access the Web service. First, you need to create a ServiceClient object using the service URL. The service client is the abstraction used to make a Web service call. Then, you call the invoke() method of the ServiceClient, passing in the name of the operation you are trying to invoke and an object array of the two operation parameters: a String for the SKU and an Integer for the quantity. The result will be a Boolean object.

That's all there is to invoking a Web service using Axis.

Putting the Service to the Test

Figure 3.2 shows a simple JSP page (/ch3/ex2/index.jsp) that uses InventoryCheckClient to access SkatesTown's Web service. You can experiment with different SKU and quantity combinations and see how SkatesTown's SW responds. You can check the responses against the contents of the product database in /resources/products.xml.

Figure 3.2 Putting the SkatesTown inventory check Web service to the test.

The inventory check example demonstrates one of the promises of Web services—you don't have to know XML to build them or to consume them. This finding validates SOAP's claim as an infrastructure technology. The mechanism that allows this to happen involves multiple abstraction layers (see Figure 3.3). Providers and requestors view services as Java APIs. Invoking a Web service requires one or more Java method invocations. Implementing a Web service requires implementing a Java backend (a class or an EJB, for example). The Web service view is one of SOAP messages being exchanged between the requestor and the provider. These are both logical views in that this is not how the requestor and provider communicate. The only "real" view is the wire-level view where HTTP packets containing SOAP messages are exchanged between the requestor's application and the provider's Web server. The miracle of software abstraction has come to our aid once again.

Figure 3.3 Layering of views in Web service invocation.

SOAP on the Wire

The powers of abstraction aside, really understanding Web services does require some knowledge of XML. Just as a highly skilled Java developer has an idea about what the JVM is doing and can use this knowledge to write higher performance applications, so must a Web service guru understand the SOAP specification and how SOAP messages are moved around between requestors and providers. This does not mean that to build or consume sophisticated or high-performance Web services you have to work with raw XML—layers can be applied to abstract your application from SOAP. However, knowledge of SOAP and the way in which a Web service engine translates Java API calls into SOAP messages and vice versa allows you to make educated decisions about how to define and implement Web services.


Luckily, the Apache Axis distribution comes with an awesome tool that can monitor the exchange of SOAP messages on the wire. The aptly named TCPMon tool will monitor all traffic on a given port. You can learn how to use TCPMon by looking at the examples installation section in /bws/readme.html.

TCPMon will either do its work as a proxy or redirect all traffic to another host and port. This ability makes TCPMon great not only for monitoring SOAP traffic but also for testing the book's examples with a backend other than Tomcat. Figure 3.4 shows TCPMon in action on the inventory check Web service. In this case, the backend is running on the Macromedia JRun J2EE application server. By default, JRun's servlet engine listens on port 8100, not on 8080 as Tomcat does. In the figure, TCPMon is set up to listen on 8080 but to redirect all traffic to 8100. Essentially, with TCPMon you can make JRun (or IBM WebSphere or BEA Weblogic) appear to listen on the same port as Tomcat and run the book's examples without any changes.

Figure 3.4 TCPMon in action.

The SOAP Request

Here is the information that passed on the wire as a result of the inventory check Web service request. Some irrelevant HTTP headers have been removed and the XML has been formatted for better readability but, apart from that, no substantial changes have been made:

POST /bws/inventory/InventoryCheck.jws HTTP/1.0
Host: localhostContent-Type: text/xml; charset=utf-8
Content-Length: 426
SOAPAction: ""

<?xml version="1.0" encoding="UTF-8"?>
         <arg0 xsi:type="xsd:string">947-TI</arg0>
         <arg1 xsi:type="xsd:int">1</arg1>

Later in the chapter, we will look in detail at all parts of SOAP. For now, a quick introduction will suffice.

The HTTP packet begins with the operation, a POST, and the target URL of the Web service (/bws/inventory/InventoryCheck.jws). This is how the requestor identifies the service to be invoked. The host is localhost ( because you are accessing the example Web service that comes with the book from your local machine. The content MIME type of the request is text/xml. This is how SOAP must be invoked over HTTP. The content length header is automatically calculated based on the SOAP message that is part of the HTTP packet's body. The SOAPAction header pertains to the binding of SOAP to the HTTP protocol. In some cases it might contain meaningful information. JWS-based Web service providers don't require it, however, and that's why it is empty.

The body of the HTTP packet contains the SOAP message describing the inventory check Web service request. The message is identified by the SOAP-ENV:Envelope element. The element has three xmlns: attributes that define three different namespaces and their associated prefixes: SOAP-ENV for the SOAP envelope namespace, xsd for XML Schema, and xsi for XML Schema instances. One other attribute, encodingStyle, specifies how data in the SOAP message will be encoded.

Inside the SOAP-ENV:Envelope element is a SOAP-ENV:Body element. The body of the SOAP message contains the real information about the Web service request. In this case, this element has the same name as the method on the Web service that you want to invoke—doCheck(). You can see that the Axis ServiceClient object auto-generated element names—arg0 and arg1—to hold the parameters passed to the method. This is fine, because no external schema or service description specifies how requests to the inventory check service should be made. In lieu of anything like that, Axis has to do its best in an attempt to make the call. Both parameter elements contain self-describing data. Axis introspected the Java types for the parameters and emitted xsi:type attributes, mapping these to XML Schema types. The SKU is a java.lang.String and is therefore mapped to xsd:string, and the quantity is a java.lang.Integer and is therefore mapped to xsd:int. The net result is that, even without a detailed schema or service description, the SOAP message contains enough information to guarantee successful invocation.

The SOAP Response

Here is the HTTP response that came back from Axis:

HTTP/1.0 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: 426

<?xml version="1.0" encoding="UTF-8"?>
         <doCheckResult xsi:type="xsd:boolean">true</doCheckResult>

The HTTP response code is 200 OK because the service invocation completed successfully. The content type is also text/xml. The SOAP message for the response is structured in an identical manner to the one for the request. Inside the SOAP body is the element doCheckResponse. Axis has taken the element name of the operation to invoke and added Response to it. The element contained within uses the same pattern but with Result appended to indicate that the content of the element is the result of the operation. Again, Axis uses xsi:type to make the message's data self-describing. This is how the service client knows that the result is a boolean. Otherwise, you couldn't have cast the result of call.invoke() to a java.lang.Boolean in Listing 3.4.

If the messages seem relatively simple, it is because SOAP is designed with simplicity in mind. Of course, as always, some complexity lurks in the details. The next several sections will take an in-depth look at SOAP in an attempt to uncover and explain all that you need to know about SOAP to become a skilled and successful Web service developer and user.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.