October 22, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Parsing XML Documents: Events, Part 2

  • February 22, 2001
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »


Preview

One of the common ways to create custom XML processing tools is through the use of an event-based parser named SAX. In the previous lesson, I introduced you to the general concept of event-driven programming. In this lesson, I will continue that introduction by walking you through a very simple event-driven program written in the Java programming language. In subsequent lessons, I will show you how to use a SAX parser with event-driven programming to parse and process XML documents.

Introduction

One way to parse an XML document is to analyze the XML document as a stream of text, recognizing the various components as they are encountered, and applying the processing algorithm as the components are recognized. A very common way to implement this approach is by using a concept (often referred to as SAX) that will examine the sequence of characters that comprise the XML text and raise events (such as the start and end of elements) as the components in the document are encountered.

An event-based parser reports events to the processing program using callbacks. The program implements and registers event  handlers for the different types of events. Code written into the event handlers is designed to achieve the overall objective of the program.

Before getting into the details of event-driven processing for XML, I am going to develop a very simple event-driven program using the Java programming language and walk you through it. There will be no XML involved in this program.  Rather, this is one of the simplest event-driven programs that I could devise.  It is presented solely for the purpose of introducing you to the concepts and code for event-driven programming.  (I will get into the use of event-driven programming for processing XML documents in a subsequent lesson.) Hopefully, this simple program will help you to understand the more complex event-driven programming used for parsing and processing XML documents.

I chose to use a visual GUI approach because most people find it easier to understand event-driven programming with visual components than with other kinds of non-visual components and events. I chose to use an applet because it is a little easier to develop an applet with a GUI than to develop other kinds of Java programs with a GUI.

A Sample Program

It could be said that 

"An event driven program is just a bunch of objects laying around waiting for an event to happen." 

Once an event-driven program is started, after some initial setup effort, the program usually goes into a quiescent state, waiting for an event to happen. When an event happens, an event handler springs into action and does some work.  Then it goes back to waiting for the next event. This raises the question, "What is an event?"  An event is the occurrence of anything of interest in the context of your program. An event-driven program that deals with a GUI might consider an event to have happened when someone clicks a button with a mouse.  (That is the case in this sample program.)

The sample program was written as an applet.  Therefore, it can be executed either by loading it into a web browser, or by loading it into a special program named AppletViewer(AppletViewer is a utility program from Sun Microsystems intended for use in testing applet programs.) I illustrated the use of the AppletViewer program for executing and applet in the previous lesson.  I will illustrate the use of a browser for executing the applet in this lesson. Figure 1 shows the screen output when the browser starts running this sample applet.  (This screen shot was taken before the user caused any events to happen.)

Figure 1. Browser screen on startup.

As you can see, the applet starts running with a red button showing on the screen.  Following startup, it does nothing until the user clicks the red button with the mouse. There are many different types of events associated with Java GUI components.  This program is designed to recognize and handle only one type of event: ActionEvent.

If the user clicks on the red button, this will cause an event of type ActionEvent to occur.  As you will see in the code samples in a later section, an ActionEvent Handler is registered on the button. When the first ActionEvent happens on the button, the event handler causes the button to turn yellow as shown in Figure 2.

Figure 2. Browser screen after first click on Button.

From this point forward, clicking the button causes the color of the button to toggle between yellow and blue, as shown in Figure 3 and Figure 4.  This toggle behavior will continue until the user terminates the program.

Figure 3. Browser screen after second click on Button

Figure 4. Browser screen after third click on Button.

What you have seen illustrated in the above figures is the behavior of a very simple event-driven program written using the Java programming language. The following sections will walk you through the Java source code for this program.  If you would like to compile and run the program for yourself, instructions for doing so are provided in the section entitled Compiling a Java Program near the end of the lesson.

The HTML File

An applet is a kind of Java program that is designed to be downloaded from a web site and executed under control of a browser.  Therefore, in order to execute an applet, you must create an HTML file that references the applet.  Then you load the HTML file into your browser (or into the AppletViewer program), causing the applet to be executed. An HTML file that can be used to execute this applet program is shown in the following listing. If you have successfully reached this point in your XML studies, you should have no difficulty understanding this simple HTML file, so I won't discuss it in detail.

<HTML>
<BODY>

<applet code="XmlEvent01.class" 
        width="300" height="50">
</applet>
</BODY>
</HTML>

Suffice it to say that the applet tag in the HTML file causes the browser to find and load an applet program file whose name is XmlEvent01.class. The applet is executed in a rectangular portion of the browser screen that has a width of 300 pixels and a height of 50 pixels.

Interesting Code Fragments

I will discuss the sample program in fragments.  A complete listing of the program is shown in a listing near the end of the lesson.

All Java code must be contained inside a class definition, and every Java program must have at least one class definition, often referred to as the controlling class. The following listing shows the beginning of the definition for the controlling class. (Although the source code for Java programs must be plain text, I have used color to highlight certain portions of this code to make it easier to discuss.)

public class XmlEvent01 extends Applet 
             implements ActionListener{


The green portion of this listing provides the name of the class, which is also the name of the program.  You will recognize this as being the same as the name of the program referred to by the applet tag in the HTML text of the earlier listing.

The red code in Listing 2 indicates inheritance. One of the advantages of Java and other object-oriented programming languages is the ability to extend existing classes in order to benefit from the code already written into those classes. In this case, the controlling class extends the existing class named Applet (Applet is a member of a standard class library provided by Sun).  In doing so, the program inherits the ability to behave in the general way that a browser expects an applet program to behave.

The dark blue code in the listing shows a construct that doesn't exist in many object-oriented programming languages, but is very important in Java.  This construct is known as implementing an interface. In this case, the interface is a pre-defined interface named ActionListener (a definition of the ActionListener interface is also contained in the standard libraries provided by Sun).

In Java event driven programming, we speak of sources and listeners.  We also say that an object is an instance of a class.

To make a long story short...

We can create (instantiate) one or more listener objects of a particular type and register them on a source. When an event of that type happens on the source, all of the registered listeners are notified of the occurrence of the event. The listeners are then free to take whatever action is appropriate in response to the event. In this program, the button will be the source of events of type ActionEvent (an event of type ActionEvent occurs each time the user clicks the button with a mouse).

We will register only one listener on the button.  The behavior of that listener will be to toggle the color of the button between yellow and blue each time it is notified that an ActionEvent has occurred on the button. In order for an object to be registered on a source as a listener for events of type ActionEvent, that object must be instantiated from a class that implements the ActionListener interface.

This program is designed to cause an object instantiated from the controlling class to be capable of being registered on the button to listen for events of type ActionEvent. Thus, the controlling class must implement the ActionListener interface, which it does.

Of necessity, the explanations of Java programming concepts in this lesson are very brief.  If you are interested in learning more about Java programming than is provided here, visit my online Java tutorials at Gamelan.  You can view a consolidated index of my Gamelan Java articles by clicking here.

As you saw in the above figures, this applet program places a red button in the browser window.  The code in the following listing creates the button as an object of the class named Button.

  Button aButton
            new Button("Toggle Color");


A reference to the Button object is saved in the reference variable named aButton (this reference variable will be used later to place the button in the browser window, and for some other purposes as well). This code also causes the caption on the button to read Toggle Color when the button appears on the screen.

When (in response to an applet tag in an HTML file) a browser  successfully finds and loads an applet program file (XmlEvent01.class in this case), it instantiates an object from the controlling class and invokes a method on the object to start the applet running.  Several methods are available for this purpose. One of the available methods is named start.  This is where the programmer can place the code that determines the behavior of the applet. The following line of code shows the beginning of the method named start in our sample program.

  public void start(){


The following line of code shows the code inside the body of the start method that causes the initial color of the button to be red.

    aButton.setBackground(Color.red);

As you can see, this line of  code uses the reference to the button named aButton to gain access to the button.  Then it invokes a particular method on the button that causes the background color of the button to be set to red.  (The background color of a button is one of the properties of a button.)

Perhaps the most abstract and cryptic portion of this program is shown in the following line of code.  (Again, I used color to make it easier to discuss this code.)

    aButton.addActionListener(this);
 

This code causes the object of the controlling class, instantiated by the browser (this), to be registered as a listener on the button. The green code is a reference to the button.  This reference is used to invoke the method named addActionListener on the button.  (The method named addActionListener is a method used for registering ActionListener objects.) The red code shows the invocation of the method named addActionListener on the button. The behavior of this method is to cause the incoming parameter (this) to be added to a list of listener objects that will be notified each time an ActionEvent occurs on the button. The blue code is a reference to the object of the controlling class instantiated by the browser (this). This reference is passed as a parameter to the method named addActionListener when that method is invoked on the button object.  Henceforth, this listener object will be notified whenever an event of the type ActionEvent occurs on the button.

Prior to this point in the program, a button object has been instantiated and prepared for use.  Its initial color has been set to red, and a listener object has been registered on it.  However, it has not yet been made visible to the user. The code in the following listing causes the button to appear in the visual output produced when the applet program executes under control of the browser.  This code adds the button to the GUI being constructed by the applet for use by the browser.

    add(aButton);

  }//end start()


This code also contains the curly brace that ends the definition of the method named start.

As mentioned earlier, any class whose objects will be used as listeners for events of type ActionEvent must implement the interface named ActionListener. Any class that implements the interface named ActionListener must provide a definition for a method named actionPerformed. When a source detects that it has been subjected to an event of type ActionEvent, it notifies all of its registered ActionListener objects that the event has occurred. The mechanism for this notification is to invoke the method named actionPerformed on each of the registered objects.

The actionPerformed method is often referred to as a callback method (call me back at this number when an ActionEvent happens). The method is also often referred to as an event handler. This is where you write the code that determines the behavior of the listener object when the event occurs. 

In our case, we want the behavior of the listener object to cause the background color of the button to toggle between yellow and blue as successive action events happen.  (The behavior could just as easily be to buy 500 shares of stock, or to turn the air conditioner on.  The behavior is whatever the author of the event handler method defines it to be.)  The code in the following listing shows the beginning of the event handler method named actionPerformed.

  public void actionPerformed(
                        ActionEvent e){

Whenever the actionPerformed method is invoked by the source on which the listener object is registered, a parameter is passed to the method containing information about the event.  For events of type ActionEvent, this parameter is a reference to an object of the class ActionEvent (now you can see why I have been referring to this as an event of the type ActionEvent).

The code in the body of the event handler method can either use the information encapsulated in that object, or can ignore it.  In this case, I didn't need to use it, so I just ignored it. The following listing shows the body of the actionPerformed method (in red).

    if(aButton.getBackground() 
                       == Color.yellow)
      aButton.setBackground(
                           Color.blue);
    else
      aButton.setBackground(
                         Color.yellow);

  }//end actionPerformed()
} //End XmlEvent01 class.

The body of this event handler method is a simple if...else statement.  The statement determines the current background color of the button and changes it to the other color (yellow to blue or blue to yellow). Since the color is neither yellow nor blue at startup (it is red), the event handler sets the background color to yellow the first time it is invoked. Each time an event of type ActionEvent occurs on the button, the button will notify this event listener object by invoking the actionPerformed method.  When that happens, the code in the body of the actionPerformed method toggles the color of the button between yellow and blue.

The code in the above listing also shows the two curly braces that end the definitions of the actionPerformed method and the XmlEvent01 class (shown in black). Since only one class was defined in this program, this listing is also the end of the program. As mentioned earlier, a complete listing of the program is provided near the end of the lesson.

This is just about the simplest event-driven program that I know how to write using Java. Hopefully this program has served its intended purpose of providing you with a stepping stone toward the use of more complex event-driven programs for parsing and processing XML documents.

Summary

In the previous lesson, I introduced you to the general concept of event-driven programming. In this lesson, I continued that introduction by walking you through a very simple event-driven program written in the Java programming language.

What's Next?

In subsequent lessons, I will show you how to use a SAX parser with event-driven programming to parse and process XML documents. I will also show you how to use a DOM parser to parse and process XML documents.

Compiling a Java Program

If you want to write your own XML processors using Java, you will need access to Java development tools.  Fortunately, everything that you will need is freely available on the web.  You won't need to purchase anything. This section describes the mechanics of installing the development tools and using them to write Java programs.

The process of developing and using Java programs consists of three steps:

  • Write the source code.
  • Compile the source code.
  • Execute the program.

There are a variety of ways that Java programs can be executed.  Earlier sections of this lesson described the execution of a Java program as an applet under control of a browser. This section describes the mechanics of execution as a stand-alone application and also describes the mechanics of execution under a browser.

The first step is to get an editor that you can use to prepare the Java source code.  Numerous editors are available free of charge.  Here are the URLs for three of them:

The Programmer's File Editor
http://www.lancs.ac.uk/people/cpaap/pfe/

Arachnophilia
http://www.arachnoid.com/arachnophilia/

JEDPlus
http://www.zdnet.co.uk/software/free/internet/java/sw33.html

The next step is to download the Java development tools known as the Java 2 platform, Standard Edition from Sun.  These tools include everything that you will need to compile and execute Java programs.  As of December 2000, the tools are available at the following URL:  http://java.sun.com/j2se/1.3/

Download the latest version that is available for your operating system. While you are there, be sure to download the documentation as well.  Also be sure to print and save the installation instructions.

The next step is to install and use the editor and the development software that you downloaded from Sun.  If you are new to computers as well as new to Java programming, you may need to get some assistance with the installation process from someone who has a little more experience in installing software.

The following box summarizes how to compile and execute a Java application.
 

HOW TO COMPILE AND EXECUTE A JAVA APPLICATION

Here are the steps, based on the assumption that you are running under Windows.  If you are running under Solaris, Mac, or some other operating system, you will need to translate these instructions to that OS. 

1.  Download and install the Java development tools from Sun.  Follow the installation instructions available from Sun.  Be sure to also download and install the documentation.

2.  Using any editor that can produce a plain text file, create a source code file with the extension on the file name being .java  This file contains your actual Java instructions.

3.  Open an MSDOS box and change directory to the directory containing the source file.  It doesn't matter which directory the source file is in, but I normally put my Java files in a directory all their own. 

4.  Assume that the name of the source file is Hello.java, just to have something definitive to refer to.  (Make sure that you get the case correct in this and all subsequent operations.)

5.  To compile the file, enter the following command at the prompt: 

javac Hello.java

6.  Correct any compiler errors that show up.  Once you have corrected all compiler errors, the javac program will execute and return immediately to the prompt with no output. 

At that point, the directory should also contain a file named Hello.class and possibly other files with a class extension as well.  These are the compiled files. 

7.  To execute the program, enter the following command: 

java Hello

If you are testing the applet described earlier in this lesson, here are the modified instructions beginning with Step 4 (everything prior to Step 4 is the same as above).
 

HOW TO COMPILE AND EXECUTE A JAVA APPLET

...

4.  Use your text editor to copy the Java source code from Listing 11 into a text file named XmlEvent01.java

(Make sure that you get the case correct in this and all subsequent operations.)

5.  To compile the file, enter the following command at the MSDOS prompt: 

javac XmlEvent01.java

6.  If you copied the file from Listing 11, you should not get any compiler errors. 

The javac program should execute and return immediately to the prompt with no output. 

At that point, the directory should also contain a file named XmlEvent01.class.  This is the compiled file. 

7.  Use your text editor to create a file named XmlEvent01.html containing the HTML file from Listing 10.  Store that file in the  directory that contains the file named XmlEvent01.class.

8.  To execute the applet under the AppletViewer program, enter the following command at the MSDOS prompt: 

AppletViewer XmlEvent01.html

9.  To execute the applet under your browser, load the file named XmlEvent01.html into your browser.
 

Complete Program Listings

A complete listings of the HTML file follows:
 

<HTML>
<BODY>

<applet code="XmlEvent01.class" 
        width="300" height="50">
</applet>
</BODY>
</HTML>

A complete listing of the Java source code follows:
 

/*File XmlEvent01.java
Illustrates event driven programming.
This is an applet.
**************************************/

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class XmlEvent01 extends Applet 
             implements ActionListener{
  //Instantiate a button object
  Button aButton = 
            new Button("Toggle Color");

  //Override the start method  
  public void start(){
    //Set initial background color for
    // the button.
    aButton.setBackground(Color.red);
    //Register an Action listener on
    // the button
    aButton.addActionListener(this);

    //Add the button to the applet
    // window
    add(aButton);

  }//end start()
    
  //Event handler callback method
  public void actionPerformed(
                        ActionEvent e){
    //Toggle color of button on Action
    // Event.
    if(aButton.getBackground() 
                       == Color.yellow)
      aButton.setBackground(
                           Color.blue);
    else
      aButton.setBackground(
                         Color.yellow);
  }//end actionPerformed()
    
} //End XmlEvent01 class.


Copyright 2000, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without  express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin (baldwin.richard@iname.com) is a college professor and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel