Home > Articles > Programming > Java

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.

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