Welcome!

Industrial IoT Authors: Gopala Krishna Behara, Sridhar Chalasani, Tirumala Khandrika, William Schmarzo, Stackify Blog

Related Topics: Industrial IoT

Industrial IoT: Article

A Client for Testing Server-Side XML Applications

A Client for Testing Server-Side XML Applications

Almost every industry today has B2B exchanges that enable businesses to improve the efficiency of some process or communication with customers, partners, or suppliers. The open and public exchanges that exist today will be replaced tomorrow with Web services, which allow direct communication between two businesses.

What these two communication methods have in common is that both receive and reply using XML. If you aren't writing these communication-enabling types of applications today, you very well may be in the future.

This article demonstrates how to:

  • Write a reusable tool for testing these types of applications.
  • Authenticate with password-protected servers.
  • Use the JDOM API.
  • Extend the tool to make it more useful.

    Overview
    One of the problems you run into when you're writing communicative applications like these is that you need to know that you're sending and receiving proper data. Most of the projects I've worked on recently are just these types of applications - and I quickly found that I needed to determine two things: (1) the validity of the data being returned, and (2) whether the server was handling the incoming data properly.

    The first - determining that the server is returning proper data - is very simple in its purest form: a request can be made via the GET method and most current browsers will render the XML that the server responds with. Although testing the validity of the response data is easy using a GET request, it is more important to know that it is responding that way as a result of being invoked with an actual request containing XML.

    Which leads me to the next point, testing to make sure your server application is handling the incoming XML documents properly. What this really means is that you want to know that your application will handle an incoming XML document, and that it will perform properly. By invoking your application with XML, you can test whether, given good input, your application will respond properly and, given bad data, whether it will behave in the manner you anticipate.

    I knew this wouldn't be the last application to require my testing the sending and receiving of XML, so I decided to write a generic tool to facilitate the process.

    The Tool
    The tool itself is simple, and I've oversimplified it by putting almost all of the client code in one class. First let's have a look at the user interface, shown in Figure 1.

    As you can tell, it's a very simple application - a button to allow you to choose an XML document, a place to type in a URL, a text box to display the results from the server, and a button to initiate the POST. A look at the code in Listing 1 gives you the following methods:

    private void getXMLFile() & private void postData()
    The method getXMLFile is called as a result of clicking on the XML File button. The method's only purpose is to pop open a FileChooser Dialog (see Figure 2) that allows you to specify the XML document you want to use for your test.

    The postData method is what actually does the most work - too much work for an individual method, but, for simplicity, all the really important code is in one place. We start by getting an instance of a DOMBuilder and calling the build() method, passing in the File object for our XML file. We then make a connection to the server identified in the URL text field of the user interface. This is accomplished with the HttpURLConnection class in the java.net package.

    After establishing our connection, we get to use a nice class provided by the JDOM API, the XMLOutputter class! First we instantiate an OutputStreamWriter, passing the HttpURLConnections getOutputStream() as a parameter to the constructor of the OutputStreamWriter. We then create an instance of the XMLOutputter class with a string representing the indent we want to use, in this case a "\t" for tabs and a boolean indicating that we'd like to use new line characters.

    Now that we have that stuff set up, we need to associate our XML document object with our outputter. The method to do this is output(Document theDocYouWantToWriteOut, OutputStreamtheActualOutputStream). After calling the output() method and a quick call to flush(), we're ready to start getting input back from the server.

    The code for this is nothing new, so I'll only touch on it by saying that we're getting the input stream from HttpURLConnection and that you can examine all this code by downloading the source.

    What we've accomplished here is an easy way to post an XML file to a server and display the results in a text box. For testing purposes I've written a servlet that pretty much echoes the content of the XML document submitted by the client. The servlet adds a node to the document named SERVER_TIME, which contains a date-time stamp as the text of that node.

    The code for the doPost() method is shown in Listing 2. The code for the servlet is simple and can also be examined in Listing 2 or by downloading the source code from this article.

    Authenticating the Use of the Authenticator Class
    One problem with these applications is that they're generally password protected - in order to access them you need to be authenticated. Thankfully, Java makes it easy to do this. In the java.net package is an Authenticator abstract class that you can subclass to create a graphical interface that allows users to provide their credentials for authentication. The code to do this same thing can be found in Chapter 7, "Retrieving Data with URLs," of Java Network Programming, 2nd Edition, by Elliotte Rusty Harold (O'Reilly). A simple overview of this class, right from the JavaDoc, is as follows:

    The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information.

    Applications use this class by creating a subclass, and registering an instance of that subclass with the system with setDefault(). When authentication is required, the system will invoke a method on the subclass (like getPasswordAuthentication). The subclass's method can query about the authentication being requested with a number of inherited methods (getRequestingXXX()), and form an appropriate message for the user.

    So, as you can see by the code below, we have the following constructor and methods:
    private void show() public PasswordAuthentication getPasswordAuthentication()
    Those methods, as well as two inner classes that handle the OK and Cancel responses (again, right from Java Network Programming), are all that's really required to add authentication to this application. The Authenticator will prompt you for credentials only when the site you're trying to access requires it, as shown in Figure 3.

    Extending the Tool
    As I mentioned, the tool itself is very basic, and is useful for testing XML-based applications. And there are quite a few ways that you can turn this application into a more effective testing tool. For example :

  • You could change the file chooser to point to a directory and load all the XML documents in that directory to be posted to the server.
  • Instead of loading static XML documents from a directory, you could write a Message Creator type class that builds XML messages with real data. Doing this doesn't prevent you from reusing the tool with other applications. All you have to do is write a Message Creatable interface and implement a new Message Creator for every new application you need to test.
  • You could use threads to make simultaneous posts to the server to test real-life loads. This could be combined with the previous suggestion to really test how your application will handle incoming requests.

    The JDOM API
    This tool was written using the JDOM (www.jdom.org) beta 6. However, none of the methods used in this application were deprecated in the beta 7 release of the JDOM API. That said, let's look at some of the classes and methods being used.

    For starters, we're using the org.jdom.Document class, which defines the methods for manipulating an XML document. I make more use of this class in the sample servlet that I've included. The method I'm using is getRootElement().

    The next class I use, the Element class, is analogous to a node in an XML document or an "element" in the document. The method addContent() is used in the Element class to add text to an element; those elements can then be added to other elements through the addContent() method, or to a document object.

    As already mentioned, I'm using two other classes, a DOMBuilder and an XMLOutputter. Together these classes allow you to (1) create a Document object from various types of inputs and (2) write a Document object out, respectively.

    Overall, the JDOM API is extremely easy to use; I may have made it seem more difficult than it truly is. The authors of JDOM have done a great job of creating a simple and effective API for working with XML.

    Conclusion
    As you can see, testing an XML-based server-side application is fairly straightforward and can be accomplished rather easily. The basic tool, combined with one or more of the suggestions for extending the tool, should help speed up the process of building and debugging server-based XML applications.

  • More Stories By Jon Strande

    Jon Strande is a consultant with Perfect Order in
    Harrisburg, PA. Jon is a Java Certified Programmer who
    has written several articles on Java and was the past
    president of his local JUG.

    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.


    @ThingsExpo Stories
    SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
    Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
    A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. 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 ov...
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
    SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
    To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
    The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
    "Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    "Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...