Java IoT Authors: Jnan Dash, Roger Strukhoff, Elizabeth White, Pat Romanski, Liz McMillan

Related Topics: Java IoT

Java IoT: Article

Tagging the Data Part 3

Tagging the Data Part 3

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.

    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"
    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 1­4. Listing 4 is the XML file for a confirmation. The 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.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.

    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 http://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.")

    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_.

    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.

    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.

  • More Stories By Ajit Sagar

    Ajit Sagar is Associate VP, Digital Transformation Practice at Infosys Limited. A seasoned IT executive with 20+ years experience across various facts of the industry including consulting, business development, architecture and design he is architecture consulting and delivery lead for Infosys's Digital Transformation practice. He was also the Founding Editor of XML Journal and Chief Editor of Java Developer's Journal.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    This month @nodexl announced that ServerlessSUMMIT & DevOpsSUMMIT own the world's top three most influential Kubernetes domains which are more influential than LinkedIn, Twitter, YouTube, Medium, Infoworld and Microsoft combined. NodeXL is a template for Microsoft® Excel® (2007, 2010, 2013 and 2016) on Windows (XP, Vista, 7, 8, 10) that lets you enter a network edge list into a workbook, click a button, see a network graph, and get a detailed summary report, all in the familiar environment of...
    IT professionals are also embracing the reality of Serverless architectures, which are critical to developing and operating real-time applications and services. Serverless is particularly important as enterprises of all sizes develop and deploy Internet of Things (IoT) initiatives. Serverless and Kubernetes are great examples of continuous, rapid pace of change in enterprise IT. They also raise a number of critical issues and questions about employee training, development processes, and opera...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
    The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility. As they do so, IT professionals are also embr...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...