HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

This is the third in a series of articles focused on using Java and ColdFusion technologies to develop an Online Ticket Store application. In the July issue of JDJ we went through the ticket reservation system for our online store. We took a look at how the actual protocol used for communicating with the airline back offices could be abstracted at the Service Access tier.

This month JDJ is focusing on XML, which brings us to an aspect of our store transactions that we haven't paid much attention to data formatting. Let's pause to think about the type of data we're transporting across the different tiers of our architecture. Primarily, the end user submits his or her search criteria for an airline ticket and gets back a response from the airline back office. During this transaction the data goes through several tiers of a distributed application. Another part of our online store is the module that offers goods for purchase or lease. (This will be developed in the next article in this series.) The data transferred in the airline store's purchase and lease transactions will undergo a route similar to the data for the ticket reservations.

To make this application scalable to different storefronts, we'll need a standard data format to represent the transaction objects, such as an airline ticket query and the corresponding confirmation. Indeed, this kind of format is one of the main reasons for XML's existence.

I'll begin with a definition of the data objects for the Online Ticket Store, which will include objects that will be used in the next article for selling and leasing goods offered in the store. Such objects include clothes and souvenirs as well as portable CD players, laptops, CDs and books that can be leased for the duration of the flight. In this article we'll encapsulate the string arguments we pass into the TicketBrokerServlet and the StoreServlet (defined in next month's article) into XML structures. The servlets will parse the XML structures into Java objects for processing in the middle and back-office tiers.

This article focuses only on data formatting for data objects using XML. As I'm assuming that readers are familiar with XML structures and parsing, I won't cover the basics here. Readers will need a basic familiarity with Java servlets to follow the discussion, but those interested in the application itself who don't care much about XML can skip forward to the next part in the series without missing anything. In the next article we'll discuss the online store part of the application, i.e., the merchandise buying and leasing operations offered by the store.

Data Interchange Formats
Our application consists of the airline reservation system and the online store. The data objects for the airline reservation system are:

  • Ticket query
  • Ticket quote
  • Booking request
  • Booking confirmation
Although the online store won't be described until the next issue, I'm going to define the objects for it now:
  • Lease order
  • Lease confirmation
  • Purchase order
  • Purchase confirmation
Note that in the above data objects there are three types of confirmations. To keep things simple, let's limit our data definitions to one confirmation structure with an attribute that indicates which operation is being confirmed.

The end-to-end interaction in our distributed application starts from the Client UI tier and ends in the Application Services tier. Figure 1 shows a breakdown of this data interaction.

Figure 1
Figure 1:

The data from the Client UI tier to the Merchant Server tier is in HTML, since our front end to the Merchant Server is a page served up by Allaire's ColdFusion (please see the corresponding issues of ColdFusion Developer's Journal, Vol. 1, issues 5 and 6). The end-user client UI can run in a browser; hence we get a virtual Internet storefront. The data representation for the interaction between the Service Access tier and the Application Services tier is going to depend on the protocol. With RMI, serialized Java objects are passed across the wire. With CORBA, CORBA structures constitute the format for the data interchange. With raw sockets and Java servlets, data is exchanged using serialized data streams.

This leaves the data interchange between the Merchant Server and the Service Access tiers. If this application were migrated to the real world, our online store would have to communicate with several airlines and airport stores. In such cases defining the data objects, e.g., Purchase Order, becomes a nightmare if each back office has its own definition of the object. Luckily, standard data formats for most industry verticals are emerging in the e-business market. The most prominent of these is XML, which holds the promise of spanning all of e-business. Similarly, if our Service Access tier were transported to another application and the data formats were different, it would be a substantial task to update our data structures to the new formats.

Data Objects for Reserving and Booking Tickets
The attributes of the ticket query and response from the airline back-office tier were defined in JDJ's July issue. The fields in the ticket query are shown below. Example values are assigned to the fields:
DEPARTURE_CITY = "Smallville"
ARRIVAL_CITY = "Gotham"
BEGIN_DATE = "31/01/1999"
END_DATE = "01/01/2000"
NUMBER = "2"
CLASS = "First"
PREFERENCE = "Window"
SMOKING = "No"

The result of this query is returned as a ticket quote from the various airline back offices to the Service Access tier, which creates a best quote and returns it to the Merchant Server tier. This quote has the following fields:

REFERENCE_NO = "SA2345678"
AIRLINE = "SeemaAir"
DEPARTURE_CITY = "Smallville"
DEPARTURE_DATE = "31/01/1999"
DEPARTURE_TIME = "10:00 P.M."
ARRIVAL_CITY = "New York"
ARRIVAL_DATE = "01/01/2000"
ARRIVAL_TIME = "1:30 A.M."
NO_OF_SEATS = "2"
CLASS = "First"
SEATING_PREFERENCE = "Window"
SMOKING = "No"
PRICE = "$1234.56"

The data structure for a booking request has the following fields:

NAME = "Clark Kent, Lois Lane"
REFERENCE_NO = "SA2345678"
AIRLINE = "SeemaAir"

A basic assumption here is that the reference number will be unique for an airline and the back office can access the details of the flight based on the confirmation number. Based on this input, the airline will send back a confirmation object with just one field:



	   CONFIRMATION_NO	  =	"SA2345678" 


The hierarchy of the XML documents in DOM for the ticket reservation operations is shown in Figure 2. The XML file is shown in Listings 14. Listing 4 is the XML file for a confirmation. The <confirmation> tag has one attribute, "Type," which indicates the type of confirmation. Our broker can return confirmations of the type "Ticket," "Lease" and "Purchase." I'm providing only an example of the ticket reservation confirmation. The confirmations for leasing and purchasing merchandise will be similar.

Figure 2
Figure 2:

Data Objects for Selling and Leasing Goods
Let's go ahead and define the attributes of goods sold in the store. An item that may be offered by the store will have the following fields (example values are assigned to the fields):

ITEM_NAME = "CD Player"
ITEM_ID = "cd30056"
QUANTITY = "2"

An order for the purchase of an item (or items) will also need information about the person making the purchase. This will consist of the following fields:

NAME = "Clark Kent"
ADDRESS = "123 Tiny Lane, Smallville, Kansas, 12345"

The fields listed above are common for both purchase and lease options. Some fields, however, are characteristic of the lease operation because the lease is going to be linked to the flight the person takes (the equipment is leased for the duration of the flight and hence must be available at the airport). So the additional fields for the lease are:

AIRPORT = "Sunita International Airport"
AIRLINE = "SeemaAir"
FLIGHT_NO = "SA 123"
DEPARTURE_DATE = "12/01/2000"

The hierarchy of the XML documents in DOM for the buy/lease operations is shown in Figure 3. The XML file is shown in Listings 5 and 6.

Figure 3
Figure 3:

Back to Basics: HTTP GET and HTTP POST
Now that we have our data object definitions, what should we do with them? To actually use the XML data structures, we need to have modules in the Merchant Server tier to send the data objects to the Service Access tier. We also need modules in the Service Access tier to parse the XML data into Java objects and then send them to the appropriate back-office tier for processing. In the case of the Merchant Server tier, the data is actually submitted via a ColdFusion template. The Service Access tier receives all requests via a servlet. The data for ticket reservations is processed by the TicketBrokerServlet (as described in the July article). The data for the merchandise purchase and leasing will be processed by the StoreServlet (described in the next article). Here we'll look at the code that parses the XML text.

So far, we've used the GET method to send data to the TicketBrokerServlet; the ticket request is sent as a parameterized query with the URL string to the server. The POST method is more flexible, however, because there are no limitations about parameter format and length. When transmitting XML structures, the length of the query string can be substantial. Some servers may limit the query string of the GET parameters to 240 characters, and the method shouldn't be used to send information to the server. Its main purpose is to read information from the server.

Hence our Java servlets need to pick up POST requests sent by the "client." In a servlet this is done by the doPost() method. Let's look at the methods in the TicketBrokerServlet that can pick up the POST request and parse the XML content into Java objects. For each XML data structure we'll need a corresponding Java object (shown in Listing 7). All the Java data objects are given in one listing to conserve space. Each data object is represented as a simple Java class with one full-argument constructor and getter methods. Typically, each object will have its own listing. As you can see, the complete code isn't given in this article; most of the objects are stubbed out. Instead, I've provided the complete code for the TicketQuery and TicketQuote objects to illustrate the XML parsing and document creation. Please refer to JDJ's Web site at www.sys-con.com/java for the complete code listing. The code for the TicketBrokerServlet that handles the TicketQuery and TicketQuote is shown in Listing 8. The listing for the merchandise purchase and leasing (not given here) will be available at the Web site.

IBM's XML Parser for Java is used for parsing the XML document that's sent via the HTTP POST request. Let's look at the doPost() method of the TicketBrokerServlet in Listing 8. (The complete code for this servlet isn't discussed here and is omitted from the listings due to space constraints. This code was discussed in the previous articles. Where the code is stubbed out, I have inserted the comments "// etc.")

TicketBrokerServlet
The request and response streams are copied into request_ and response_ variables for future use. Next, the method parseParameters() is called. This method parses the input parameters and creates the appropriate Java object. The XML processing for this application is done in the XMLProcessor class (Listing 9). The TicketBrokerServlet first creates a new instance of the XMLProcessor object. It then calls the initParser() method on the TicketStoreXML class. The servlet's input stream is passed in as a parameter for the parser to parse the XML document that the servlet received in its input stream.

Next, the method getQueryType() is called on the XMLProcessor reference (xp) to check what kind of an operation was invoked on the TicketBrokerServlet. If the type is a "TicketQuery," the method processTicketQuery() is called, which returns a TicketQuery object from the XML document. Following this, the local method processQuery() is called. This method goes across to the Application Services tier and gets back a TicketQuote.

The method processQuery() was discussed in the previous article. I have stubbed out the functionality to keep the listing short and focused. To test the code, a TicketQuote is created directly. In the application a call to getQuotes() will be made to the clientManager_; this will return a vector of quotes, and the local getBestQuote() method would be called to obtain the best quote. The end result is the same. We get an object that encapsulates the best quote from the back-office tiers.

The next call made on the xp is processTicketQuote(). This takes in the TicketQuote object we just obtained and returns a String, which is the corresponding XML document that needs to be sent back to the Merchant Server tier. This is appended to the result_ string and the string is written back via the servlet's output stream, toClient_.

XMLProcessor
Finally, let's look at the class that does all the XML work. Note that this class imports classes from the packages com.ibm.xml parser and org.w3c.dom. The former contains the classes for IBM's XML for Java parser. The latter contains the W3C classes for XML documents.

The method initParser() creates a new instance of the XMLParser. Next, the data is read in from the InputStream, input, which is actually the TicketBrokerServlet's input stream. Finally, the root of the document is initialized.

The method processTicketQuery() is called from the TicketBrokerServlet's processQuery() method. This method extracts the data from the XML document received via the POST method and uses it to construct a TicketQuery object. It returns the TicketQuery object to the calling method.

The first few lines of the method call the local method processSingleTag(), a utility method for processing a single tag in an XML document. Next, the Date element is parsed. The begin and end dates are created as strings beginDate and endDate. Once the dates are parsed, the data is used to create and return a new TicketQuery object to the TicketBrokerServlet.

The next two methods are utility methods that aid in parsing XML documents. The processSingleTag() method is a utility method that takes in a tag String and an XML Element and returns its text value. A NodeIterator is created and the first element in the list is extracted from the Element that was passed in as an argument. Finally, the text value of this extracted element is passed back. The processListTag() method is similar, except that the code iterates through a list of elements and passes back a Vector of Elements to the calling method. The NodeIterator class is used for this purpose.

The last method in this class is used to create an XML document from a TicketQuote object, which is passed in as an argument to the method. A new TXDocument is created and the root element ("TicketQuote") is created and inserted into the document. Next, the version for XML is set. This is followed by a declaration of variables representing various levels of the XML document structure. The XML document is going to be three levels deep so three TXElements are created. The rest of the method creates and adds the elements to the tree. The values for the elements are obtained from the "quote" variable passed in as the argument to this method. The first element is the "ReferenceNo." The "child" variable is initialized to a new "referenceNo" TXElement object. Next, the text value for this element is obtained from the quote object by calling getReferenceNo(). This is added to the child element, which in turn is added to the root element.

The rest of the method adds other elements in a similar fashion. In the case of the Date elements, the tree is three levels deep. Hence the grandChild and greatGrandChild variable are used. At the end of the method, the document is written to a StringWriter variable and returned to the calling method.

Conclusion
We've now been through the entire exercise of creating XML documents for transporting data from one tier of a distributed application to another, converting that XML document into a language-specific object, sending it across to another tier, getting back another object, converting this new object to an XML document and transporting it back to the original tier. What have we gained? We've certainly added a lot of overhead by using XML tags instead of plain strings.

Well, the big gain is in standardization and clarity in data formatting. In the next couple of years, if all goes well, XML standards will start solidifying in the marketplace for several industry verticals. These standards will help provide universal definitions of data structures such as a "Reservation" or an "Order." Indeed, such standards are already appearing in today's marketplace.

As for the overhead, that's a price we'll have to pay for the benefits of standardization. Take TCP/IP, for instance. When I first looked at a TCP packet, I was shocked to discover that for each character of the login I sent across the wire, the stack added 53 characters that encapsulated the data in the packet. However, think of the universality that standards such as TCP have brought to the computing world.

Author Bio
Ajit Sagar, a member of the technical staff at i2 Techologies in Dallas, Texas, holds an MS in computer science and a BS in electrical engineering. He focuses on Web-based e-commerce applications and architectures. Ajit is a Sun-certified Java programmer with nine years of programming experience, including two and a half in Java.
Ajit can be reached at [email protected].

	

Listing 1: 

<?xml version="1.0"?> 
<TicketQuery> 
 <DepartureCity>Smallville</DepartureCity> 
 <ArrivalCity>Gotham</ArrivalCity> 
 <Date> 
  <BeginDate> 
   <Year>1999</Year> 
   <Month>12</Month> 
   <Day>31</Day> 
  </BeginDate> 
  <EndDate> 
   <Year>2000</Year> 
   <Month>1</Month> 
   <Day>1</Day> 
  </EndDate> 
 </Date> 
 <NoOfSeats>2</NoOfSeats> 
 <Class>First</Class> 
 <SeatingPreference>Window<SeatingPreference> 
 <SmokingPreference>No<SmokingPreference> 
</TicketQuery> 

Listing 2: 

<?xml version="1.0"?> 
<TicketQuote> 
 <ReferenceNo>"SA2345678"</ReferenceNo> 
 <Airline>SeemaAir</Airline> 
 <DepartureCity>Smallville</DepartureCity> 
 <ArrivalCity>Gotham</ArrivalCity> 
 <Date> 
  <DepartureDate> 
   <Year>1999</Year> 
   <Month>12</Month> 
   <Day>31</Day> 
  </DepartureDate> 
  <DepartureTime> 
   <Hour>22</Hour> 
   <Minutes>00</Minutes> 
  </DepartureTime> 
  <ArrivalDate> 
   <Year>2000</Year> 
   <Month>1</Month> 
   <Day>1</Day> 
  </ArrivalDate> 
  <ArrivalTime> 
   <Hour>1</Hour> 
   <Minutes>30</Minutes> 
  </ArrivalTime> 
 </Date> 
 <NoOfSeats>2</NoOfSeats> 
 <Class>First</Class> 
 <SeatingPreference>Window<SeatingPreference> 
 <SmokingPreference>No<SmokingPreference> 
 <Price>"$1234.56"</Price> 
</TicketRequest> 

Listing 3: 

<?xml version="1.0"?> 
<BookingRequest> 
 <ReferenceNo>"SA2345678"</ReferenceNo> 
 <Airline>SeemaAir</Airline> 
 <NameList> 
  <Name> 
   <LastName>"Kent"</LastName> 
   <FirstName>"Clark"</FirstName> 
       </Name> 
  <Name> 
   <LastName>"Lane"</LastName> 
   <FirstName>"Lois"</FirstName> 
       </Name> 
 </NameList> 
</BookingRequest> 

Listing 4: 

<?xml version="1.0"?> 
<Confirmation Type="Ticket"> 
 <ConfirmationNo>"SA2345678"</ConfirmationNo> 
</Confirmation> 

Listing 5: 

 <?xml version="1.0"?> 
<Lease> 
   <Passenger> 
       <Name> 
            <LastName>"Kent"</LastName> 
            <FirstName>"Clark"</FirstName> 
       </Name> 
   </Passenger> 
   <Flight> 
        <ReferenceNo>"SA2345678"</ReferenceNo> 
        <Airport>"Sunita International Airport"</Airport> 
        <Airline>"SeemaAir"</Airline> 
        <FlightNumber>"SA 123"<FlightNumber> 
        <Date> 
           <Year>1999</Year> 
           <Month>12</Month> 
           <Day>31</Day> 
        </Date> 
    </Flight> 
    <ItemList> 
        <ItemName>"CD Player"</ItemName> 
        <ItemId>cd00321</ItemId> 
        <Quantity>1</Quantity> 
        <ItemName>"Book"</Book> 
        <ItemId>bookx453</ItemId> 
        <Quantity>1</Quantity> 
    </ItemList> 
</Lease> 

Listing 6: 

<?xml version="1.0"?> 
<Purchase> 
   <Name> 
       <LastName>"Kent"</LastName> 
       <FirstName>"Clark"</FirstName> 
   </Name> 
   <Address> 
       <Street>"123 Tiny Lane"</Street> 
       <City>"Smallville"</City> 
       <State>"Kansas"</State> 
       <Country>USA</Country> 
       <ZIP>12345</ZIP> 
   </Address> 
   <ItemList> 
        <ItemName>"CD Player"</ItemName> 
        <ItemId>cd00321</ItemId> 
        <Quantity>1</Quantity> 
        <ItemName>"Book"</Book> 
        <ItemId>bookx453</ItemId> 
        <Quantity>1</Quantity> 
    </ItemList> 
</Purchase> 
  

Listing 7: Data Object for the Online Ticket Store 

import java.io.Serializable; 
import java.text.ParseException; 
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class DataObjects { 
} 

// file TicketQuery.java 
class TicketQuery implements Serializable { 
  
  DateFormat df_ = DateFormat.getDateInstance(); 

  // Fields for a ticket query 
  private long queryId_ = 0; 
  private String departureCity_ = null; 
  private String arrivalCity_ = null; 
  private Date beginDate_ = null; // Acceptable begin date and time for flight query 
  private Date endDate_ = null;   // Acceptable end date and time for flight query. 
  
  private int noOfSeats_ = 0; 
  private String seatClass_ = null;  //  coach, business, first class 
  private boolean aisle_ = false;    // window, aisle 
  private boolean smoking_ = false;  // smoking/non-smoking 

  /** 
   * Full-arg constructor 
   */ 
  public TicketQuery (String departureCity, 
       String arrivalCity, 
       String beginDate, 
       String endDate, 
       String noOfSeats, 
       String seatClass, 
       String aisle, 
       String smoking) { 
  
 // Generate new query ID 
 queryId_ = generateQueryId(); 
  
 departureCity_ = departureCity; 
 arrivalCity_ = arrivalCity; 
  
 // The date Strings need to be parsed 
 setBeginDate(beginDate); 
 setEndDate(endDate); 
 setNoOfSeats(noOfSeats); 
 setSeatClass(seatClass); 
 setAisle(aisle); 
 setSmoking(smoking); 
  } 
  
  /** 
   * The current time is used to generate the queryId. This way, we get 
   * a time stamp of when the query was made. 
   */ 
  public long generateQueryId () { 
   return System.currentTimeMillis(); 
  } 
  
  // 
  // -- Setter methods are required for these fields 
  
  /** 
   * 
   */ 
  public void setBeginDate (String beginDate) { 
   try { 
    beginDate_ = df_.parse(beginDate); 
   } 
   catch (ParseException pe) { 
  pe.printStackTrace(); 
   } 
  } 
  
  public void setEndDate (String endDate) { 
   try { 
          endDate_ = df_.parse(endDate); 
   } 
      catch (ParseException pe) { 
    pe.printStackTrace(); 
   } 
  } 
  
  public void setNoOfSeats(String noOfSeats) { 
   noOfSeats_ = Integer.parseInt(noOfSeats); 
  } 
  
  public void setSeatClass (String seatClass) { 
   seatClass_ = seatClass; 
  } 
  
  public void setAisle (String aisle) { 
   if (aisle.equalsIgnoreCase("YES")) 
    aisle_ = true; 
   else 
    aisle_ = false; 
  } 
  
  public void setSmoking(String smoking) { 
   if (smoking.equalsIgnoreCase("YES")) 
    smoking_ = true; 
   else 
    smoking_ = false; 
  } 

  // 
  // -- Getter methods for all the fields. 
  // 
  
  public long getQueryId () { 
   return queryId_; 
  } 
  
  public String getDepartureCity () { 
   return departureCity_; 
  
  } 
  
  public String getArrivalCity () { 
   return arrivalCity_; 
  } 
  
  public Date getBeginDate () { 
   return beginDate_; 
  } 
  
  public Date getEndDate () { 
   return endDate_; 
  } 
  
  public int getNoOfSeats () { 
   return noOfSeats_; 

  } 
  
  public String getSeatClass () { 
   return seatClass_; 

  } 
  
  public boolean isAisle () { 
   return aisle_; 

  } 
  
  public boolean isSmoking () { 
   return smoking_; 

  } 
} 

// file TicketQuote.java 
class TicketQuote implements Serializable { 
  
  SimpleDateFormat sdf_ = new SimpleDateFormat(); 
  
  // Fields for a ticket query 
  private String referenceNo_ = null; 
  private String airline_ = null; 
  private String departureCity_ = null; 
  private String arrivalCity_ = null; 

  // The Date fields include the time values also 
  private Date departureDate_ = null; 
  private Date arrivalDate_ = null; 
  
  private int noOfSeats_ = 0; 
  private String seatClass_ = null;  //  coach, business, first class 
  private boolean aisle_ = false;    // window, aisle 
  private boolean smoking_ = false;  // smoking/non-smoking 
  private String price_ = "$0.00"; 

  /** 
   * Full-arg constructor 
   */ 
  public TicketQuote (String referenceNo, 
       String airline, 
       String departureCity, 
       String arrivalCity, 
       Date departureDate, 
       Date arrivalDate, 
       int noOfSeats, 
       String seatClass, 
       boolean aisle, 
       boolean smoking, 
       String price) { 
  
 referenceNo_ = referenceNo; 
 airline_ = airline; 
 departureCity_ = departureCity; 
 arrivalCity_ = arrivalCity; 
 departureDate_ = departureDate_; 
 arrivalDate_ = arrivalDate_; 
 noOfSeats_ = noOfSeats; 
 seatClass_ = seatClass; 
 aisle_ = aisle; 
 smoking_ = smoking; 
 price_ = price; 
  } 
  
  // 
  // -- Getter methods for all the fields. 
  // 
  
  public String getReferenceNo () { 
   return referenceNo_; 
  } 
  
  public String getAirline () { 
   return airline_; 
  } 
  
  public String getDepartureCity () { 
   return departureCity_; 
  
  } 
  
  public String getArrivalCity () { 
   return arrivalCity_; 
  } 
  
  public Date getDepartureDate () { 
   return departureDate_; 
  } 
  
  public Date getArrivalDate () { 
   return arrivalDate_; 
  } 
  
  public int getNoOfSeats () { 
   return noOfSeats_; 

  } 
  
  public String getSeatClass () { 
   return seatClass_; 

  } 
  
  public boolean isAisle () { 
   return aisle_; 

  } 
  
  public boolean isSmoking () { 
   return smoking_; 

  } 
  
  public String getPrice () { 
   return price_; 
  } 
} 

// PLEASE GO TO www.sys-con.com/java FOR THE FOLLOWING CODE 

class Name {} 
class BookingRequest {} 
class Confirmation {} 
class Address {} 
class Item {} 
class Lease {} 
class Purchase {} 

Listing 8: TicketBrokerServlet.java 

import java.io.*; 
import java.util.*; 
import java.rmi.*; 

import javax.servlet.http.*; 
import javax.servlet.*; 

public class TicketBrokerServlet extends HttpServlet 
{ 
  protected HttpServletRequest request_ = null; 
  protected HttpServletResponse response_ = null; 
  protected StringBuffer result_ = null; 
  
  XMLProcessor xp_ = null; 
  
  PrintWriter toClient_ = null; 
  
  // TicketClientManager clientManager_ = null; 
  
  
  public void doPost (HttpServletRequest request, 
                      HttpServletResponse response) 
    throws ServletException, IOException { 
 try { 

      request_ = request; 
      response_ = response; 

   // Get a reference to the output stream 
      toClient_ = new PrintWriter(response_.getOutputStream()); 

      if (toClient_ == null) { 
        response_.sendError(1, "Null toClient_ stream"); 
   } 
  
      // etc. 
  
   result_ = new StringBuffer(); 
   processParameters(); 
  
   toClient_.println(result_.toString()); 
 } 
 catch (Exception e) { 
   e.printStackTrace(); 
 } 
  } 
  
  private void processParameters () { 
 // Create a new XMLProcessor to convert XML to Java objects. 
 xp_ = new XMLProcessor(); 
  
 try { 
   xp_.initParser(request_.getInputStream()); 
 } 
 catch (IOException ioe) { 
   ioe.printStackTrace(); 
 } 
  
 String queryType = xp_.getQueryType(); 
 if (queryType.equals("TicketQuery")) { 
  TicketQuery ticketQuery = xp_.processTicketQuery(); 
  processQuery(ticketQuery); 
 } 
 else if (queryType.equals("BookingRequest")) { 
  // BookingRequest bookingRequest = xp_.processTicketBooking(); 
  // processBooking(bookingRequest); 
 } 
  } 

  /** 
   * 
   */ 
  private void processQuery (TicketQuery query) { 
 Vector quotes = null; 
  
 // !! Stubbed code. Typically, this will be replaced by a call 
 // !! to the appropriate client via the TicketClientManager. 
  
 // etc. 
  
 TicketQuote ticketQuote = new TicketQuote("SA123456", "SeemaAir", 
             "SmallVille", "Gotham", 
             new Date("1999.12.31"), 
             new Date("2000.1.1"), 
             2, "First", false, false, "$1234.56"); 
  
 String xmlQuote = xp_.processTicketQuote(ticketQuote); 
  
 result_.append(xmlQuote); 
  } 
  
  /** 
   * Process a booking request. 
   */ 
  private void processBooking (BookingRequest bookingRequest) { 
 // etc. 
  } 
  

  /** 
   * Return best quote from the quotes obtained from the Application 
   * Services tier 
   */ 
  private TicketQuote getBestQuote (Vector quotes) 
  { 
   // etc. 
   return null; 
  } 
  
} 

Listing 9: XML processor for the Online Ticket Store 

import com.ibm.xml.parser.*; 
import org.w3c.dom.*; 
import java.io.*; 
import java.util.*; 
import Order; 
import Promise; 
import AtomicDate; 
import AtomicOrder; 

public class XMLProcessor { 
  Document doc_; 
  TXElement root_; 
  
  /** 
   * Initialize the XML parser and document 
   */ 
  public void initParser(InputStream input) 
  { 
    Parser p = new Parser("XMLParser"); 
    doc_ = p.readStream(input); 
    root_ = (TXElement) doc_.getDocumentElement(); 
  } 
  
  public String getQueryType () { 
   return root_.getName(); 
  } 

  public TicketQuery processTicketQuery () 
  { 
    String departureCity = processSingleTag("DepartureCity", root_); 
    String arrivalCity =  processSingleTag("ArrivalCity", root_); 
 String noOfSeats = processSingleTag("NoOfSeats", root_); 
 String seatClass = processSingleTag("Class", root_); 
 String seatingPref = processSingleTag("SeatingPreference", root_); 
 String smokingPref = processSingleTag("SmokingPreference", root_); 
  
  
 TXElement txe = null; 
  
 NodeIterator iterator1 = root_.getElementsByTagName("Date"); 
  
 // There is only one Date element 
 TXElement dateElement = (TXElement)iterator1.toFirstNode(); 
  
 NodeIterator iterator2 = dateElement.getElementsByTagName("BeginDate"); 
  
 TXElement beginDateElement = (TXElement)iterator2.toFirstNode(); 
  
 String beginYear = processSingleTag("Year", beginDateElement); 
 String beginMonth = processSingleTag("Month", beginDateElement); 
 String beginDay = processSingleTag("Day", beginDateElement); 
  
 String beginDate = beginYear + "." + beginMonth + "." + beginDay; 
  
 iterator2 = dateElement.getElementsByTagName("EndDate"); 
  
 TXElement endDateElement = (TXElement)iterator2.toFirstNode(); 
  
 String endYear = processSingleTag("Year", endDateElement); 
 String endMonth = processSingleTag("Month", endDateElement); 
 String endDay = processSingleTag("Day", endDateElement); 
  
    String endDate = endYear + "." + endMonth + "." + endDay; 
  
    return new TicketQuery(departureCity, arrivalCity, beginDate, endDate, 
         noOfSeats, seatClass, seatingPref, smokingPref); 
  
  } 
  
  /** 
   * Process a single tag from an XML document 
   */ 
  
  public String processSingleTag(String tag, Element startNode) { 
    TXElement e; 
    Node n; 
    String textValue = null; 
    NodeIterator iter = startNode.getElementsByTagName(tag); 

    int length = iter.getLength(); 

    if (length != 1) { 
      System.out.println("Houston we have a problem with tag: " + tag); 
    } 
 else { 
      n = iter.toFirstNode(); 
      e = (TXElement) n; 
      textValue = e.getText(); 
    } 

    return textValue; 
  } 
  
  /** 
   * Process a list of tags from an XML document 
   */ 

  public Vector processListTag(String tag, Element startNode) 
  { 
    TXElement e, cElement, cTemp; 
    Node n; 
    Vector list = null; 
    String text; 

 System.out.println("tag = " + tag + ", startNode = " + startNode); 
    NodeIterator iter = startNode.getElementsByTagName(tag); 

    int length = iter.getLength(); 

    if (length != 0) 
    { 
      list = new Vector(); 
    } 

    for (int i = 0; i < length; i++) 
    { 
      n = iter.moveTo(i); 
      e = (TXElement) n; 
      list.addElement(e); 
    } 
    return list; 
  } 

  /** 
   * Create an XML document from the TicketQuote object 
   */ 
  public String processTicketQuote (TicketQuote quote) 
  { 
    TXDocument doc = new TXDocument(); 
    TXElement root = new TXElement("TicketQuote"); 
    doc.insert(root, 0); 
    doc.setVersion("1.0"); 

    TXElement child, grandChild, greatGrandChild; 
    TXText text; 

    child = new TXElement("ReferenceNo"); 
    text = new TXText((quote.getReferenceNo()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 
  
    child = new TXElement("Airline"); 
    text = new TXText((quote.getAirline()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 

    child = new TXElement("DepartureCity"); 
    text = new TXText((quote.getDepartureCity()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 

    child = new TXElement("ArrivalCity"); 
    text = new TXText((quote.getArrivalCity()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 

    child = new TXElement("Date"); 
    root.addElement(child); 
  
 grandChild = new TXElement("DepartureDate"); 
    child.addElement(grandChild); 

 Date date = quote.getDepartureDate(); 
  
 greatGrandChild = new TXElement("Year"); 
 text = new TXText(String.valueOf(date.getYear())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 greatGrandChild = new TXElement("Month"); 
 text = new TXText(String.valueOf(date.getMonth())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 greatGrandChild = new TXElement("Day"); 
 text = new TXText(String.valueOf(date.getDay())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 grandChild = new TXElement("ArrivalDate"); 
    child.addElement(grandChild); 

 date = quote.getArrivalDate(); 
  
 greatGrandChild = new TXElement("Year"); 
 text = new TXText(String.valueOf(date.getYear())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 greatGrandChild = new TXElement("Month"); 
 text = new TXText(String.valueOf(date.getMonth())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 greatGrandChild = new TXElement("Day"); 
 text = new TXText(String.valueOf(date.getDay())); 
 greatGrandChild.addTextElement(text); 
    grandChild.addElement(greatGrandChild); 
  
 child = new TXElement("NoOfSeats"); 
 text = new TXText(String.valueOf(quote.getNoOfSeats())); 
    child.addTextElement(text); 
    root.addElement(child); 

 child = new TXElement("Class"); 
    text = new TXText((quote.getSeatClass()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 

 child = new TXElement("SeatingPreference"); 
 text = new TXText(String.valueOf(quote.isAisle())); 
    child.addTextElement(text); 
    root.addElement(child); 

 child = new TXElement("SmokingPreference"); 
 text = new TXText(String.valueOf(quote.isSmoking())); 
    child.addTextElement(text); 
    root.addElement(child); 

 child = new TXElement("Price"); 
    text = new TXText((quote.getPrice()).toString()); 
    child.addTextElement(text); 
    root.addElement(child); 

 StringWriter dString = new StringWriter(); 
    doc.printWithFormat(new PrintWriter(dString)); 
 return dString.toString(); 
  } 
} 


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.