Home > Articles > Programming > Java

This chapter is from the book

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(
            "",
            "doCheck",
            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.

TCPMon

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"?>
<SOAP-ENV:Envelope 
   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Body>
      <doCheck>
         <arg0 xsi:type="xsd:string">947-TI</arg0>
         <arg1 xsi:type="xsd:int">1</arg1>
      </doCheck>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

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 (127.0.0.1) 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"?>
<SOAP-ENV:Envelope 
   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" 
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Body>
      <doCheckResponse>
         <doCheckResult xsi:type="xsd:boolean">true</doCheckResult>
      </doCheckResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

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.

InformIT Promotional Mailings & Special Offers

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

Overview


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

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

Collection and Use of Information


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

Questions and Inquiries

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

Online Store

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

Surveys

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

Contests and Drawings

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

Newsletters

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

Service Announcements

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

Customer Service

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

Other Collection and Use of Information


Application and System Logs

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

Web Analytics

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

Cookies and Related Technologies

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

Do Not Track

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

Security


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

Children


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

Marketing


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

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

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

Correcting/Updating Personal Information


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

Choice/Opt-out


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

Sale of Personal Information


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

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

Supplemental Privacy Statement for California Residents


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

Sharing and Disclosure


Pearson may disclose personal information, as follows:

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

Links


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

Requests and Contact


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

Changes to this Privacy Notice


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

Last Update: November 17, 2020