Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Purchase Order Submission Web Service

Recall that when Al Rosen of Silver Bullet Consulting was investigating SkatesTown's e-business processes, he noticed that one area that badly needed automation was purchase order submission. Purchase orders and invoices were being exchanged over e-mail, and they were manually input into the company's purchase order system.

Because SkatesTown already has defined an XML schema for its purchase orders and invoices, Al thinks it makes sense to build a purchase order Web service that accepts a purchase order as an XML document and returns an XML invoice. This service would be an example of 1-to-1 direct messaging using a request-response interaction pattern.

Purchase Order and Invoice Schemas

The schemas for SkatesTown's purchase orders and invoices are explained in detail in Chapter 2. Listings 3.8 and 3.9 show example XML document instances for both.

Listing 3.8  Example SkatesTown Purchase Order

<po xmlns="http://www.skatestown.com/ns/po" 
    id="50383" submitted="2001-12-06">
   <billTo>
      <company>The Skateboard Warehouse</company>
      <street>One Warehouse Park</street>
      <street>Building 17</street>
      <city>Boston</city>
      <state>MA</state>
      <postalCode>01775</postalCode>
   </billTo>
   <shipTo>
      <company>The Skateboard Warehouse</company>
      <street>One Warehouse Park</street>
      <street>Building 17</street>
      <city>Boston</city>
      <state>MA</state>
      <postalCode>01775</postalCode>
   </shipTo>
   <order>
      <item sku="318-BP" quantity="5">
         <description>Skateboard backpack; five pockets</description>
      </item>
      <item sku="947-TI" quantity="12">
         <description>Street-style titanium skateboard.</description>
      </item>
      <item sku="008-PR" quantity="1000"/>
   </order>
</po>

Listing 3.9  Example SkatesTown Invoice

<invoice inv="http://www.skatestown.com/ns/invoice" 
             id="50383" submitted="2001-12-06">
   <billTo>
      <company>The Skateboard Warehouse</company>
      <street>One Warehouse Park</street>
      <street>Building 17</street>
      <city>Boston</city>
      <state>MA</state>
      <postalCode>01775</postalCode>
   </billTo>
   <shipTo>
      <company>The Skateboard Warehouse</company>
      <street>One Warehouse Park</street>
      <street>Building 17</street>
      <city>Boston</city>
      <state>MA</state>
      <postalCode>01775</postalCode>
   </shipTo>
   <order>
      <item sku="318-BP" quantity="5" unitPrice="49.95">
         <description>Skateboard backpack; five pockets</description>
      </item>
      <item sku="947-TI" quantity="12" unitPrice="129.00">
         <description>Street-style titanium skateboard.</description>
      </item>
      <item sku="008-PR" quantity="1000" unitPrice="0.00">
         <description>Promotional: SkatesTown stickers</description>
      </item>
   </order>
   <tax>89.89</tax>
   <shippingAndHandling>89.89</shippingAndHandling>
   <totalCost>1977.52</totalCost>
</invoice>

XML-Java Data Mapping

Unfortunately, Al Rosen finds out that the actual SkatesTown purchase order system does not know how to deal with XML. The XML capabilities were added as an extension to the system by a developer who has since left the company. To make matters worse, much of the source code pertaining to XML processing seems to have been lost during an upgrade of the source control management (SCM) system at the company.

The PO system's APIs work in terms of a set of Java beans representing concepts such as product, purchase order, invoice, address, and so on. Figure 3.15 shows a UML diagram.

Figure 3.15 UML model for the PO system's data objects.

Al knows that because he is using SOAP-based messaging, the task of mapping the purchase order XML to Java objects and the invoice Java objects back to XML is left entirely up to him. Therefore, he implements a serializer and a deserializer that know how to encode and decode objects from the com.skatestown.data package to and from XML. Because the schemas for purchase orders and invoices are relatively simple, he decided to do this by hand rather than to rely on available schema compiler tools; he had no experience with these. The two classes that he builds are Serializer and Deserializer in the com.skatestown.xml package. The combined code size is slightly over 300 lines of Java code.

Listing 3.10 shows the key purchase order deserialization methods. They use a number of simple utility methods such as getValue() and getElements() to traverse the DOM representation of a purchase order and construct a purchase order and all its contained objects. Reusable functionality, such as reading the common properties of POItem and InvoiceItem or creating addresses, is put in separate methods (readItem() and createAddress(), respectively). This pattern for XML to Java data mapping is very simple and readable yet flexible to handle a large variety of input XML formats.

Listing 3.10  Core Purchase Deserialization Methods

protected void readDocument(BusinessDocument doc, Element elem)
{
    doc.setId(Integer.parseInt(elem.getAttribute( "id" )));
    doc.setDate(elem.getAttribute("submitted"));
    
    doc.setBillTo(createAddress(getElement(elem, "billTo")));
    doc.setShipTo(createAddress(getElement(elem, "shipTo")));
}

protected void readItem(POItem item, Element elem)
{
    item.setSKU(elem.getAttribute("sku"));
    item.setQuantity(Integer.parseInt(elem.getAttribute("quantity")));
    item.setDescription( getValue( elem, "description" ) );
}

protected Address createAddress(Element elem)
{
    Address addr  = new Address();
    addr.setName( getValue( elem, "name" ) );
    addr.setCompany( getValue( elem, "company" ) );
    addr.setStreet( getValues( elem, "street" ) );
    addr.setCity( getValue( elem, "city" ) );
    addr.setState( getValue( elem, "state" ) );
    addr.setPostalCode( getValue( elem, "postalCode" ) );
    addr.setCountry( getValue( elem, "country" ) );
    return addr;
}

protected PO _createPO(Element elem)
{
    PO po = new PO();
    
    readDocument(po, elem);
    
    Element[] orderItems = getElements(elem, "item");
    POItem[] items = new POItem[orderItems.length];
    for (int i = 0 ; i < items.length; ++i)
    {
        POItem item = new POItem();
        readItem(item, elem);
        items[i] = item;
    }
    po.setItems(items);
    
    return po;
}

Listing 3.11 shows the key invoice serialization methods. In this case, they traverse the Java data structures describing an invoice and use utility methods such as addChild() to construct a DOM tree representing an invoice document. Again, shared functionality such as serializing an address is separated in methods that are called from multiple locations.

Listing 3.11  Core Invoice Serialization Methods

protected void writeDocument(BusinessDocument bdoc, Element elem)
{
    elem.setAttribute("id", ""+bdoc.getId());
    elem.setAttribute("submitted", bdoc.getDate());
    writeAddress(bdoc.getBillTo(), addChild(elem, "billTo"));
    writeAddress(bdoc.getShipTo(), addChild(elem, "shipTo"));
}

protected void writeAddress(Address addr, Element elem)
{
    addChild(elem, "name", addr.getName());
    addChild(elem, "company", addr.getCompany());
    addChildren(elem, "street", addr.getStreet());
    addChild(elem, "city", addr.getCity());
    addChild(elem, "state", addr.getState());
    addChild(elem, "postalCode", addr.getPostalCode());
    addChild(elem, "country", addr.getCountry());
}

protected void writePOItem(POItem item, Element elem)
{
    elem.setAttribute("sku", item.getSKU());
    elem.setAttribute("quantity", ""+item.getQuantity());
    addChild(elem, "description", item.getDescription());
}

protected void writeInvoiceItem(InvoiceItem item, Element elem)
{
    writePOItem(item, elem);
    elem.setAttribute("unitPrice", nf.format(item.getUnitPrice()));
}

protected void writeInvoice(Invoice invoice, Element elem)
{
    writeDocument(invoice, elem);
    Element order = addChild(elem, "order");
    InvoiceItem[] items = invoice.getItems();
    for (int i = 0; i < items.length; ++i)
    {
        writeInvoiceItem(items[i], addChild(order, "item"));
    }
    
    addChild(elem, "tax", nf.format(invoice.getTax()));
    addChild(elem, "shippingAndHandling", 
        nf.format(invoice.getShippingAndHandling()));
    addChild(elem, "totalCost", nf.format(invoice.getTotalCost()));
}

Service Requestor View

The PO Web service client implementation follows the same pattern as the invoice checker clients (see Listing 3.12). The goal of its API is to hide the details of Axis-specific APIs from the service requestor. Therefore, the invoke() method takes an InputStream for the purchase order XML and returns the generated invoice as a string. Alternatively, the invoke() method might have been written to take in and return DOM documents.

Listing 3.12  PO Submission Web Service Client

package ch3.ex4;

import java.io.*;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.client.ServiceClient;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;

/**
 * Purchase order submission client
 */
public class POSubmissionClient
{
    /**
     * Target service URL
     */
    private String url;
    
    /**
     * Create a client with a target URL
     */
    public POSubmissionClient(String targetUrl)
    {
        url = targetUrl;
    }
    
    /**
     * Invoke the PO submission web service
     *
     * @param po Purchase order document
     * @return Invoice document
     * @exception Exception I/O error or Axis error
     */
    public String invoke(InputStream po) throws Exception
    {
        // Send the message
        ServiceClient client = new ServiceClient(url);
        client.setRequestMessage(new Message(po, true));
        client.invoke();
        
        // Retrieve the response body
        MessageContext ctx = client.getMessageContext();
        Message outMsg = ctx.getResponseMessage();
        SOAPEnvelope envelope = outMsg.getAsSOAPEnvelope();
        SOAPBodyElement body = envelope.getFirstBody();
        
        // Get the XML from the body
        StringWriter w = new StringWriter();
        SerializationContext sc = new SerializationContext(w, ctx);
        body.output(sc);
        return w.toString();
    }
}

Sending the request message is simple. We have to create a ServiceClient from the target URL and set its request message to a message constructed from the purchase order input stream. The second parameter to the Message constructor, the boolean true, is an indication that the input stream represents the message body as opposed to the whole message. Calling invoke() sends the message to the Web service.

The second part of the method has to do with retrieving the body of the response message. This code should be familiar from the implementation of the E-mail header handler.

Finally, we use an Axis serialization context to write the XML in the response body into a StringWriter. We could have easily gotten the body as a DOM element by calling is getAsDOM() method. The trouble is, there is no standard way in DOM Level 2 to convert a DOM element into a string! Java API for XML Processing (JAXP) defines such a mechanism in its transformation API (javax.xml.transform package), but the method is fairly cumbersome. It is easiest to use an Axis SerializationContext object.

Service Provider View

The implementation of the purchase order submission service is very simple (see Listing 3.13). Because this is not an RPC-based service, the input and output are both XML documents (represented via DOM Document objects). The input document is deserialized to produce a purchase order object. It is passed to the actual PO processing backend. Its implementation is not shown here because it has nothing to do with Web services. It looks up item prices by their SKU, calculates totals based on item quantities, and adds tax and shipping and handling. The resulting invoice object is serialized to produce the result of the purchase order submission service.

Listing 3.13  Purchase Order Submission Web Service

package com.skatestown.services;

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.axis.MessageContext;
import com.skatestown.backend.*;
import com.skatestown.data.*;
import com.skatestown.xml.*;
import bws.BookUtil;

/**
 * Purchase order submission service
 */
public class POProcess
{
    /**
     * Submit a purchase order and generate an invoice
     */
    public Document submitPO(MessageContext msgContext, Document inDoc)
    throws Exception
    {
        // Create a PO from the XML document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        PO po = Deserializer.createPO(inDoc.getDocumentElement());
        
        // Get the product database
        ProductDB db = BookUtil.getProductDB(msgContext);
        
        // Create an invoice from the PO
        POProcessor processor = new POProcessor(db);
        Invoice invoice = processor.processPO(po);
        
        // Serialize the invoice to XML
        Document newDoc = Serializer.writeInvoice(builder, invoice);
        
        return newDoc;
    }
}

Finally, adding deployment information about the new service involves making a small change to the Axis Web services deployment descriptor (see Listing 3.14). Again, Chapter 4 will go into the details of Axis deployment descriptors.

Listing 3.14  Deployment Descriptor for Inventory Check Service

<!-- Chapter 3 example 4 services -->
<service name="POSubmission" pivot="MsgDispatcher">
  <option name="className" value="com.skatestown.services.POSubmission"/>
  <option name="methodName" value="doSubmission"/>
</service>

Putting the Service to the Test

A simple JSP test harness in ch3/ex4/index.jsp (see Figure 3.16) tests the purchase order submission service. By default, it loads /resources/samplePO.xml, but you can modify the purchase order on the page and see how the invoice you get back changes.

Figure 3.16 Putting the PO submission Web service to the test.

SOAP on the Wire

With the help of TCPMon, we can see what SOAP messages are passing between the client and the Axis engine:

POST /bws/services/POSubmission HTTP/1.0
Host: localhost
Content-Length: 1169
Content-Type: text/xml; charset=utf-8
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>
      <po xmlns="http://www.skatestown.com/ns/po" 
         id="50383" submitted="2001-12-06">
         ...
      </po>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The target URL is /bws/services/POSubmission. The response message simply carries an invoice inside it, much in the same way that the request message carries a purchase order. As a result, there is no need to show it here.

That's all there is to taking advantage of SOAP-based messaging. Axis makes it very easy to define and invoke services that consume and produce arbitrary XML messages.

Figure 3.17 shows one way to think about the interaction of abstraction layers in SOAP messaging. It is modeled after Figure 3.3 earlier in the chapter but includes the additional role of a service developer. As before, the only "real" on-the-wire communication happens between the HTTP client and the Web server that dispatches a service request to Axis.

Figure 3.17 Layering of abstraction for SOAP messaging.

The abstractions at this level are HTTP packets. At the Axis level, the abstractions are SOAP messages with some additional context. For example, on the provider side, the target service is determined by the target URL of the HTTP packet. This piece of context information is "attached" to the actual SOAP message by the Axis servlet that listens for HTTP-based Web service requests. The job of a service-level developer is to create an abstraction layer that maps Java APIs to and from SOAP messages. During SOAP messaging, a little more work needs to happen at this level than when doing RPCs. The reason is that data must be manually encoded and decoded by both the Web service client and the Web service backend. Finally, at the top of the stack on both the requestor and provider sides sits the application developer who is happily insulated from the fact that Web services are being used and that Axis is the Web service engine. The application developer needs only to understand the concepts pertaining to his application domain—in this case, purchase orders and invoices.

  • + Share This
  • 🔖 Save To Your Account