Java IoT Authors: Pat Romanski, Elizabeth White, Zakia Bouachraoui, Liz McMillan, Yeshim Deniz

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
    In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
    The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
    Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
    To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
    "The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    "MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
    The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...