- Creating Applications with Java API for XML Parsing (JAXP)
- Understanding XML
- XML Related Tools
- Creating an XML Document
- Creating a Document Type Definition (DTD)
- Parsing with the Simple API for XML (SAX)
- Parsing with the Document Object Model (DOM)
- An XML Version of the CruiseList Application
- Summary
An XML Version of the CruiseList Application
Once we are comfortable with our ability to verify that an XML document is correct and turn it into an object that can be manipulated in a program, we begin to ask questions about how to integrate this technology into a real application.
The biggest question is how to move the XML document from where it was created to the server where it will be consumed. The answer is simply that the XML document is a file full of characters (ASCII, Unicode, or some similar character set). Any transport that can move a text file can move an XML file.
XML and the Java Message Service (JMS) are a nice fit. All that you have to do to send XML via JMS is to place the XML into a string. This string can then be sent as a message. Messaging provides guaranteed delivery across heterogeneous operating system platforms. For more information on using messaging, see Chapter 7, "Java Message Service (JMS)," and Chapter 6, "Message-Driven Beans (MDB)."
The goal of this chapter, though, is to present Java-based XML processing to you as clearly as possible. It would be unwise to mix a JMS discussion in the same chapter. Therefore, we will create the CruiseList application here as a shared directory application.
The CruiseList GUI will create the XML document and place it in a special directory. The TicketAgent application will wake up periodically and look for files in that directory. It will open each file that it finds, create the tickets in the database, and send a response back to the GUI. The GUI will display the response in a dialog whenever the Check button is pressed.
NOTE
Before running this application, first run the AccessJDBC2 application included as part of Appendix A. This application drops and adds tables to the database along with enough data to make the application work. It can also be used to reset the database between successive runs of the program.
The code for the CruiseList GUI is shown in Listing 3.5.
Listing 3.5 The CruiseList Application
package unleashed.ch3; /* * CruiseList.java * * Created on December 31, 2001, 6:35 PM */ import unleashed.TicketRequest2; import javax.swing.*; import java.awt.event.ActionListener; import javax.swing.border.EtchedBorder; import java.awt.Container; import java.awt.BorderLayout; import java.sql.*; import javax.naming.*; import java.util.*; import java.io.*; import org.w3c.dom.*; import org.xml.sax.*; import javax.xml.parsers.*; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * * @author Stephen Potts * @version */ public class CruiseList extends JFrame implements ActionListener { Document doc; //JDBC variables java.sql.Connection dbConn = null; Statement statement1 = null; //GUI Variables JList customerList; JList cruisesAvailable; JButton btnBook; JButton btnExit; JButton btnCheck; //Arrays to hold database information int[] custNums = null; String[] lastNames = null; String[] firstNames = null; int[] cruiseIDs = null; String[] cruiseDestinations = null; String[] cruisePorts = null; String[] cruiseSailings = null; /** Constructors for CruiseList */ public CruiseList() throws Exception { init(); } public CruiseList(String caption) throws Exception { super(caption); init(); } //The init() method moves processing out of the constructors where //Exception handling is simpler private void init() throws Exception { try { //Obtain connections to JDBC and JMS via JNDI ConnectToServices(); //configure the Frame setBounds(150,200,500,250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the layout BorderLayout border = new BorderLayout(); Container content = getContentPane(); content.setLayout(border); //Populate the customerNames string String getCustomerString = "SELECT CustomerID, LastName, FirstName FROM CruiseCustomer"; ResultSet custResults = statement1.executeQuery(getCustomerString); custNums = new int[20]; lastNames = new String[20]; firstNames = new String[20]; int index = 0; while (custResults.next()) { custNums[index] = custResults.getInt("CustomerID"); firstNames[index] = custResults.getString("FirstName"); lastNames[index] = custResults.getString("LastName"); index += 1; } String[] customerNames = new String[index]; for (int i=0;i<index;i++) { customerNames[i] = firstNames[i] + " " + lastNames[i]; } int numCustomers = index; System.out.println("The number of customers " + index); //Populate the cruises string String getCruiseString = "SELECT CruiseID, Destination, Port, Sailing FROM Cruises"; ResultSet cruiseResults = statement1.executeQuery(getCruiseString); cruiseIDs = new int[20]; cruiseDestinations = new String[20]; cruisePorts = new String[20]; cruiseSailings = new String[20]; index = 0; while (cruiseResults.next()) { cruiseIDs[index] = cruiseResults.getInt("CruiseID"); cruiseDestinations[index] = cruiseResults.getString("Destination"); cruisePorts[index] = cruiseResults.getString("Port"); cruiseSailings[index] = cruiseResults.getString("Sailing"); index += 1; } String[] cruises = new String[index]; for (int i=0;i<index;i++) { cruises[i] = cruiseDestinations[i] + " Departs: " + cruisePorts[i] + " " + cruiseSailings[i]; } int numCruises = index; System.out.println("The number of cruises" + index); //More GUI components String labelString = " Customer"; labelString += " Cruise"; JLabel label1 = new JLabel(labelString); customerList = new JList(customerNames); cruisesAvailable = new JList(cruises); btnBook = new JButton("Book"); btnCheck = new JButton("Check"); btnExit = new JButton("Exit"); btnBook.addActionListener(this); btnExit.addActionListener(this); btnCheck.addActionListener(this); JPanel bottomPanel = new JPanel(); JPanel centerPanel = new JPanel(); centerPanel.add(new JScrollPane(customerList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); centerPanel.add(new JScrollPane(cruisesAvailable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); bottomPanel.add(btnBook); bottomPanel.add(btnCheck); bottomPanel.add(btnExit); content.add(label1, BorderLayout.NORTH); content.add(centerPanel, BorderLayout.CENTER); content.add(bottomPanel, BorderLayout.SOUTH); setVisible(true); }catch(Exception e) { System.out.println("Exception thrown " + e); } finally { try { //close all connections if (statement1 != null) statement1.close(); if (dbConn != null) dbConn.close(); } catch (SQLException sqle) { System.out.println("SQLException during close(): " + sqle.getMessage()); } } } private void ConnectToServices() { try { // ============== Make connection to database ============ //load the driver class Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Specify the ODBC data source String sourceURL = "jdbc:odbc:CruiseTicket"; //get a connection to the database dbConn =DriverManager.getConnection(sourceURL); //If we get to here, no exception was thrown System.out.println("The database connection is " + dbConn); System.out.println("Making connection...\n"); //Create the statement statement1 = dbConn.createStatement(); } catch (Exception e) { System.out.println("Exception was thrown: " + e); } } /** * @param args the command line arguments */ public static void main(String args[]) { //create an instance of the GUI try { CruiseList mainWindow = new CruiseList("Cruise Ticket System"); }catch(Exception e) { System.out.println("Exception in main " + e); } } public void actionPerformed(java.awt.event.ActionEvent ae) { try { Container c = btnExit.getParent(); if (ae.getActionCommand().equals("Exit")) { System.exit(0); } //Try and book a ticket if (ae.getActionCommand().equals("Book")) { System.out.println("Book was clicked"); int custIndex = customerList.getSelectedIndex(); int cruiseIndex = cruisesAvailable.getSelectedIndex(); if (custIndex == -1 || cruiseIndex == -1) { JOptionPane.showMessageDialog(c, "You must choose a customer and a cruise"); }else { //Pop up a dialog asking how many tickets String numTickets = JOptionPane.showInputDialog(c, "How many tickets?"); int numberOfTickets = Integer.parseInt(numTickets); //create a ticket request object TicketRequest2 tickReq = new TicketRequest2(custNums[custIndex], lastNames[custIndex], firstNames[custIndex], cruiseIDs[cruiseIndex], cruiseDestinations[cruiseIndex], cruisePorts[cruiseIndex], cruiseSailings[cruiseIndex], numberOfTickets, false); //create the xml file createXMLDoc(tickReq); } } //See if you got a mail message back if (ae.getActionCommand().equals("Check")) { //Check to see if there are any email messages for us fetchMessages(); } }catch (Exception e) { System.out.println("Exception thrown = " + e); } } private void fetchMessages() { try { Container c = btnExit.getParent(); //read the text message from the file String dirName = "c:/XML/response/"; File dir = new File(dirName); File f1; String messageLine = ""; String strToken = ""; String message = ""; String message2 = ""; String[] fileList = dir.list(); for (int i=0;i<fileList.length;++i) { String fileName = dirName + fileList[i]; BufferedReader br = new BufferedReader( new FileReader(fileName)); while( (messageLine = br.readLine()) != null) { message += messageLine; System.out.println("messageLine = " + messageLine); } StringTokenizer st = new StringTokenizer(message , "<>"); while (st.hasMoreTokens()) { strToken = st.nextToken(); if (strToken.equals("ticketResponse")) { message2 = st.nextToken(); //show the message in a dialog box JOptionPane.showMessageDialog(c, message2); } } } }catch (Exception e) { System.out.println(" Exception " + e); } } public void createXMLDoc(TicketRequest2 tr2) throws IOException { try { DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); doc = dBuilder.newDocument(); //Create the root element Element ticketRequest = doc.createElement("ticketRequest"); doc.appendChild(ticketRequest); //create the customer node Node customer = createCustomer(doc, tr2); ticketRequest.appendChild(customer); //create the cruise node Node cruise = createCruise(doc, tr2); ticketRequest.appendChild(cruise); //Create a transformer to write the file out TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(ticketRequest); //Write out the file String filename = "c:/XML/request/request" + tr2.getCustID() + ".xml"; StreamResult result = new StreamResult( new FileOutputStream(filename)); transformer.transform(source, result); }catch(Exception e) { System.out.println("Exception e" + e); } } private Node createCustomer(Document doc, TicketRequest2 tr2) { Element lastName = doc.createElement("lastName"); Element firstName = doc.createElement("firstName"); lastName.appendChild(doc.createTextNode(tr2.getLastName())); firstName.appendChild(doc.createTextNode(tr2.getFirstName())); Element customer = doc.createElement("customer"); Attr custIDAttribute = doc.createAttribute("custID"); String s1 = String.valueOf(tr2.getCustID()); custIDAttribute.setValue(s1); //append the attribute customer.setAttributeNode( custIDAttribute ); customer.appendChild(lastName); customer.appendChild(firstName); return customer; } private Node createCruise(Document doc, TicketRequest2 tr2) { Element destination = doc.createElement("destination"); Element port = doc.createElement("port"); Element sailing = doc.createElement("sailing"); Element numberOfTickets = doc.createElement("numberOfTickets"); destination.appendChild(doc.createTextNode(tr2.getDestination())); port.appendChild(doc.createTextNode(tr2.getPort())); sailing.appendChild(doc.createTextNode(tr2.getSailing())); String s3 = String.valueOf(tr2.getNumberOfTickets()); numberOfTickets.appendChild(doc.createTextNode(s3)); Element cruise = doc.createElement("cruise"); Attr cruiseIDAttribute = doc.createAttribute("cruiseID"); String s2 = String.valueOf(tr2.getCustID()); cruiseIDAttribute.setValue(s2); //append the attribute cruise.setAttributeNode(cruiseIDAttribute); cruise.appendChild(destination); cruise.appendChild(port); cruise.appendChild(sailing); cruise.appendChild(numberOfTickets); return cruise; } }
This application is a little long, but it is not very difficult. It uses XML to communicate its requests. It is a simple GUI that populates the variables in a TicketRequest2 object that we introduced earlier in the chapter. After the object is built, the method
public void createXMLDoc(TicketRequest2 tr2) throws IOException
is called. It takes the data in the TicketRequest2 object and creates an XML document out of it. This document is saved in a file in a special directory.
The other interesting part is checking for responses. Whenever the Check button is clicked, a separate directory is examined, all the files in that directory are opened, and a message is created and then displayed. The code to do this is shown here:
String[] fileList = dir.list(); for (int i=0;i<fileList.length;++i) { String fileName = dirName + fileList[i]; BufferedReader br = new BufferedReader(new FileReader(fileName)); while( (messageLine = br.readLine()) != null) { message += messageLine; System.out.println("messageLine = " + messageLine); } StringTokenizer st = new StringTokenizer(message , "<>"); while (st.hasMoreTokens()) { strToken = st.nextToken(); if (strToken.equals("ticketResponse")) message2 = st.nextToken(); } //show the message in a dialog box JOptionPane.showMessageDialog(c, message2); }
The entire contents of the file that it reads in are in the form
<ticketResponse> The ticket to Hawaii for Skelton was successful </ticketResponse>
This looks like XML, but there is no prolog before the data. In reality, this is a simple text file that borrows its syntax from XML. Notice how StringTokenizer can be used and <> set as the delimiter. You can step through the file looking for a tag called ticketResponse. When you find it, the next token will be the contents of that tag, complete with whitespace.
This technique is useful when your needs are so simple that using either SAX or DOM is overkill. You can quickly find what you are looking for as long as the file doesn't contain too many attributes and nested tags.
The other half of this application is the TicketAgent. This application has no GUI, and in this version, it runs through the request files just once. The code for the TicketAgent application is shown in Listing 3.6.
Listing 3.6 The TicketAgent Application
/* * TicketAgent.java * * Created on January 21, 2002, 4:37 PM */ package unleashed.ch3; import unleashed.TicketRequest2; import java.io.*; import java.util.*; import java.sql.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.*; /** * The TicketAgent application. It received an XML TicketRequest file * It uses JDBC to access the database to * get the credit card number.It then sends a message to the PaymentAgent * to request approval of a charge to the credit card. When the * charge is approved TicketAgent updates the database and sends * a message to the CruiseList application. * * * @author Steve Potts */ public class TicketAgent { static int ticketID = 7000; private boolean quit = false; //JDBC variables java.sql.Connection dbConn = null; Statement statement1 = null; String sourceURL = "jdbc:odbc:CruiseTicket"; DocumentBuilderFactory factory; DocumentBuilder builder; Document document; TicketRequest2 tr2; String eleName; public TicketAgent() throws Exception { init(); } //The init() method moves processing out of the constructors where //Exception handling is simpler private void init() throws Exception { try { //Obtain connections to JDBC and JMS via JNDI ConnectToServices(); }catch(Exception e) { System.out.println("Exception thrown " + e); } } private void ConnectToServices() { try { // ============== Make connection to database ============== //load the driver class Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //connect to the XML parser factory and builder factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); } catch (Exception e) { System.out.println("Exception was thrown: " + e); } } public void checkForXMlDocs() { String dirName = "c:/XML/request/"; File dir = new File(dirName); File f1; String[] fileList = dir.list(); for (int i=0;i<fileList.length;++i) { String s = fileList[i]; if (s.startsWith("r")) { System.out.println(fileList[i]); parseFile(dirName + fileList[i]); System.out.println(tr2); } } } public void parseFile(String fname) { try { tr2 = new TicketRequest2(); File f1 = new File(fname); document = builder.parse(f1); traverse(document); //get the credit card number from the database String ccNum = getCreditCardNumber(tr2.getCustID()); System.out.println("The Credit Card Number is " + ccNum); //create a queue send to the Payment queue if (verifyCreditCard(ccNum)) { createTicket(tr2); sendTicketResponse(tr2, true); }else sendTicketResponse(tr2, false); }catch (SAXException sxe) { Exception e = sxe; if (sxe.getException() != null) e = sxe.getException(); e.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }//parseFile private void traverse(Node cNode) { switch (cNode.getNodeType() ) { case Node.DOCUMENT_NODE: System.out.println("Element " + cNode.getNodeName()); processChildren( cNode.getChildNodes()); break; case Node.ELEMENT_NODE: eleName = cNode.getNodeName(); System.out.println("Element " + eleName); NamedNodeMap attributeMap = cNode.getAttributes(); int numAttrs = attributeMap.getLength(); for (int i=0; i<attributeMap.getLength(); i++) { Attr attribute = (Attr)attributeMap.item(i); String attrName = attribute.getNodeName(); String attrValue = attribute.getNodeValue(); storeElementValue(attrName, attrValue); } if (eleName.equals("isCommissionable")) { storeElementValue("isCommissionable", ""); } processChildren( cNode.getChildNodes()); break; case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: System.out.println("Text " + cNode.getNodeValue()); if (! cNode.getNodeValue().trim().equals("")) { System.out.println("eleName " + eleName); System.out.println("Text " + cNode.getNodeValue()); storeElementValue(eleName, cNode.getNodeValue()); } break; } } private void processChildren(NodeList nList) { if(nList.getLength() != 0) { for (int i=0; i<nList.getLength(); i++) traverse(nList.item(i)); } } private void storeElementValue(String elementName, String elementValue) { if (elementName.equals("ticketRequest")) { } if (elementName.equals("custID")) { tr2.setCustID(Integer.parseInt(elementValue)); } if (elementName.equals("lastName")) { tr2.setLastName(elementValue); } if (elementName.equals("firstName")) { tr2.setFirstName(elementValue); } if (elementName.equals("cruiseID")) { tr2.setCruiseID(Integer.parseInt(elementValue)); } if (elementName.equals("destination")) { tr2.setDestination(elementValue); } if (elementName.equals("port")) { tr2.setPort(elementValue); } if (elementName.equals("sailing")) { tr2.setSailing(elementValue); } if (elementName.equals("numberOfTickets")) { String numberOfTicketsString = elementValue; int numberOfTickets = Integer.parseInt(numberOfTicketsString); tr2.setNumberOfTickets(numberOfTickets); } if (elementName.equals("isCommissionable")) { tr2.setCommissionable(true); } } public String toString() { return tr2.toString(); } //This method sends a message to the response queue private void sendTicketResponse(TicketRequest2 tr, boolean isSuccessful) { try { //Create a message using this object String tickResp = "The ticket to " + tr.getDestination() + " for " + tr.getLastName(); if (isSuccessful) tickResp += " was successful"; else tickResp += " was not successful"; System.out.println(tickResp); //Write the response char quote = '"'; BufferedWriter bw = new BufferedWriter( new FileWriter("c:/XML/response/response" + tr2.getCustID() + ".xml")); bw.write(System.getProperty("line.separator")); bw.write("<ticketResponse>"); bw.write(System.getProperty("line.separator")); bw.write(tickResp); bw.write(System.getProperty("line.separator")); bw.write("</ticketResponse>"); bw.flush(); bw.close(); System.out.println("Created the Ticket Response Message"); }catch(Exception e) { System.out.println("Exception " + e); } } //This method creates a database entry for the new ticket private void createTicket(TicketRequest2 tr) throws Exception { //get a connection to the database dbConn =DriverManager.getConnection(sourceURL); //If we get to here, no exception was thrown System.out.println("The database connection is " + dbConn); System.out.println("Making connection...\n"); //Create the statement statement1 = dbConn.createStatement(); String insertStatement; ticketID += 1; insertStatement = "INSERT INTO CruiseTicket VALUES(" + ticketID + "," + Integer.toString(tr.getCustID()) + ", 'Unleashed Cruise Line'," + "'USS SeaBiscuit', '" + tr.getPort() + "','" + tr.getSailing() + "'," + "999.99," + "0,"+ "0,"+ "'')"; statement1.executeUpdate(insertStatement); System.out.println("Update was successful CustID = " + tr.getCustID()); statement1.close(); dbConn.close(); } private String getCreditCardNumber(int CustID) throws Exception { //get a connection to the database dbConn =DriverManager.getConnection(sourceURL); //If we get to here, no exception was thrown System.out.println("The database connection is " + dbConn); System.out.println("Making connection...\n"); //Create the statement statement1 = dbConn.createStatement(); String ccNum = ""; //Populate the creditcard string string String getCCString = "SELECT CreditCardNumber FROM CruiseCustomer " + "WHERE CustomerID = " + Integer.toString(CustID); ResultSet ccResults = statement1.executeQuery(getCCString); while (ccResults.next()) { ccNum = ccResults.getString("CreditCardNumber"); } statement1.close(); dbConn.close(); return ccNum; } private boolean verifyCreditCard(String ccNum) { int firstNum = Integer.parseInt(ccNum.substring(0,1)); if ( firstNum > 4) return false; else return true; } /** * main() method. * * @exception Exception if execution fails */ public static void main(String[] args) throws Exception { try { TicketAgent ta = new TicketAgent(); ta.checkForXMlDocs(); }catch (Exception e) { System.out.println("Exception in main() " + e); } }
NOTE
Please notice that there are two hard-coded filenames in Listing 3.6. If you are running on a non-Windows platform you will need to modify these references.
This application is a combination of a fairly simple extraction of data from a TicketRequest2 object and the creation of a ticket in the database. It is combined with XML DOM parsing code that is almost identical to the TicketRequestDOMParser class that we looked at in great detail earlier in the chapter. After the processing is done, a new message is created and placed in a special directory where the CruiseList application will look for it.
Figure 3.1 shows the CruiseList GUI.
Figure 3.1 The CruiseList application uses XML to formulate the message requesting tickets.
When the Check button is clicked, if a message is waiting, a dialog box will appear indicating whether the request was granted, as shown in Figure 3.2.
Figure 3.2 The CruiseList application uses a dialog to communicate the response back to the user.
From this example, we see how XML can be created on the fly and written to a file. We also see how the document consumer can use JAXP to parse the document and update the database.