Home > Articles

This chapter is from the book

This chapter is from the book

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.1Figure 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.2Figure 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020