Java IoT Authors: Liz McMillan, Jason Bloomberg, Elizabeth White, Yeshim Deniz, Zakia Bouachraoui

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
    @CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
    Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...
    Rafay enables developers to automate the distribution, operations, cross-region scaling and lifecycle management of containerized microservices across public and private clouds, and service provider networks. Rafay's platform is built around foundational elements that together deliver an optimal abstraction layer across disparate infrastructure, making it easy for developers to scale and operate applications across any number of locations or regions. Consumed as a service, Rafay's platform elimi...
    The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
    In today's enterprise, digital transformation represents organizational change even more so than technology change, as customer preferences and behavior drive end-to-end transformation across lines of business as well as IT. To capitalize on the ubiquitous disruption driving this transformation, companies must be able to innovate at an increasingly rapid pace.
    Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Day 2 Keynote at 17th Cloud Expo, Sandy Ca...
    New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
    According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.