HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Java programs can be classified as either Java applications or Java applets, based on the modules' execution content. While applets require the presence of a Java-enabled browser (or an AppletViewer), applications are designed to run on the client machine on the top of the Java interpreter, without the need for special helper applications.

Separating applets and applications into two disjoined sets creates inefficiency in software design, since programs designed to enrich browser pages are usually not part of Java applications.

In this article, we propose a method to include applets as part of applications. We discuss the similarities and differences between the execution of applets and applications, and offer a brief outline on applet design. And we propose a simple solution for adding applets with limited functionality to Java applications. Next, we present a brief discussion on application level resource management, such as caching images, audio clip data, and designing efficient class loader objects. Lastly, we offer a more complete solution by introducing security issues and network image access as well as design and implementation issues of applet stubs and context.

Applets and Applications
We will now present a short discussion and comparison of the execution of Java applications and Java applets. We assume that the reader has a general knowledge of object-oriented programming and also familiarity with Java class inheritance hierarchy.

Applications
Java applications are designed to run on the client machine without the need for a Java-enabled browser. Such programs must contain a public function, main(), which serves as an entry point for the execution. The executing interpreter is responsible for calling main() only once, when the program execution begins; the rest is up to the programmer.

Applications using network services, such as sockets, are responsible for implementing and maintaining program security and integrity at the application level. User-level security proves to be adequate for stand-alone applications, since during the execution of such programs, the environment can only exercise the privileges of the user who initiated the execution.

Applets
Unlike applications, the execution of applets require special java-enabled browsers or appletviewers. The core of the applet is composed of four methods, as described below. These methods are automatically called by the browsers.

  • Applet.init() - When an applet is first loaded into the system, the init() method is called by the execution environment to initialize the applet. Because this function is called once, before the applet becomes visible, it serves as a setup method, for initializing class instance variables.
  • Applet.start() - This method is called by the browser whenever the applet becomes active. The applet can be activated when the applet first starts up, or when the HTML page containing the applet tag is revisited. Whenever applets include multi-threaded execution, this method is used to create or resume the running threads.
  • Applet.stop() - When the user leaves a page containing the applet tag, the browser calls this stop method. Threads and network connections are usually suspended when this method is called.
  • Applet.destroy() - This method is called by the browser whenever an applet is to be discarded. A call to destroy is followed by the eviction of the applet instance from memory, hence this method is used mainly for cleanup purposes.
These methods are called by the browser in the specified order. It is impossible to make the call to the start method, if the applet has not been initialized. The diagram in Figure 1 illustrates in steps the execution of Java applets.

Figure 1
Figure 1

While init() and destroy() are called only once, at the beginning and the end of the execution respectively, the applet must be ready to respond to start() and stop() at all times. To improve system performance, when threads and network connections are used, these resources should be suspended and/or freed up upon the call to the stop() method.

Using Applets as Panels
An important change to the alpha version of JDK was the modification of the inheritance tree of the Applet class. In the previous versions, the Applet class was derived from Object, which made it impossible to add applets to the Layout-Manager's container and to display the applet within the application's frame.

The applet class in JDK version 1.0 is derived from Panel, which in a few steps derived from Component. This allows the programmer to add an applet to the application as a separate panel, place or paint other components on applets, etc. This section offers a discussion on design and implementation issues of including applets into applications.

Loading Applets
Although applets are usually designed to be used within browser applications and are therefore inheritably loaded across the network, for the sake of simplicity, our first example only considers applets loaded from the local file-system. This can be accomplished by calling the forName() method. To instantiate the newly loaded class, a call to the newInstance() method must be made. As the example in Listing 1 illustrates, this part of the code must be included within a try block to catch all exceptions that the class-loader might throw.

Once the applet is successfully loaded into the system, it can be inserted into the frame of the main application, using the add() method of the active LayoutManager. At this point, since the applet has not been initialized nor started, this component should be invisible. To assure this, the applet.hide() method should be called. At this point the applet is ready to run.

Running the Applet
Since the program is no longer embedded inside a browser, it is the responsibility of the application to call the init() and start() methods. Because the execution of the application frame must continue without significant interruption, the designer of the applet must make sure that both of these methods will return. If the code does not implement immediate return, another option is to spawn off a separate thread of the application to execute the applet initialization functions. With the proper synchronization, one thread can initialize the applet, while the other can continue the execution of the main application.

After the start() method returns, the applet is ready to be shown. The last step is to resize the applet to the desired dimensions. Finally, the applet.show() method is called, as suggested in the code segment shown in Listing 2. The call to the validate() method on the last line is necessary to repaint the applet and to ensure that the applet is correctly displayed by the layout manager.

Suspend and Resume
Since the applet is no longer running within a browser, the application must call the stop() and start() methods when necessary. When an application is minimized, resources used by the applets can be suspended or freed. Similarly, when the application is restored, the execution of the applets must be resumed.

Applications can respond to events such as minimize and restore by overriding the handleEvent function of the application's main frame. The code segment in Listing 3 illustrates this procedure.

Other events, such as destroying the window, can be handled in the code fragment in Listing 3 as well. In this particular example, the applications should call the stop() and destroy() methods respectively to ensure the proper execution and cleanup for all applets.

Applet Stubs and Context
Because it is the browser's responsibility to manage system resources, such as image and audio data, this functionality is not included in the applet's implementation. The applets are created within AppletStubs and AppletContext, special interfaces, that handle loading documents and images across the network. Hence to offer full networking functionality for the embedded applets, the application's frame must implement these two interfaces.

Applet Context
The AppletContext interface corresponds to the applet's execution environment. It is used to load and cache images, and display document content and status information. One of the abstract functions defined in this interface is getImage(), which takes a reference to a URL class specifying the location of the image to be loaded. When the applet needs to load an image from either the local file-system or the network, it must call the AppletContext's getImage() function to handle this task.

Because loading images over the network can be time and resource consuming, the application should implement a caching scheme to eliminate redundant loads. This is usually accomplished by using a hashtable of Image objects. When the applet requests an image, the application first searches the hashtable to see if the specified image has already been loaded. If not, it must make the necessary URL connection to load the image data across the network, otherwise a reference to the hashtable entry is returned. The code in Listing 4 demonstrates this implementation of application level caching.

Audio data and other resources can be handled in the same manner. To offer improved performance, the application should also implement a security verification algorithm, that ensures the image in the cache actually contains the same data as the URL source.

Applet Stubs
The AppletStub class is used to implement an applet viewer. One of the most important functionalities of this interface is the getParameter() method. Applet parameters are usually passed from the HTML document containing the applet tag using the param option. Because applets are no longer running in the browser's environment, an appropriate algorithm must be implemented by the application to supply the applets with parameter values.

Because applications most often receive their parameters from either the command line or from an initialization file, these input sources must be parsed and the appropriate parameters and values must be passed onto the applets. The code segment in Listing 5 offers one of many implementations of passing parameters from the application to embedded applets, using a system-wide hash table, that contains the parameter information.

Applet Security
The implementation described previously involves loading images and possibly classes over the network from remote sites. The method obviously suffers from the lack of system security because stand-alone Java applications allow the client to connect to any host and download unrestricted data and class content. Applications therefore should implement necessary applet security using the SecurityManager class.

Installing a new security manager; however, will affect the functionality of the entire application. Every network connection can and should be verified by the application, and possibly rejected if the remote site is classified as untrustworthy. The design and implementation of the SecurityManager is a complex task and this topic is currently under study.

Conclusion
Allowing Java applets, normally designed only for web pages, to be included in applications can improve software reuse. In this article, we offered an approach for allowing applets to be merged into frames of stand-alone Java applications. Although the simple method of treating the applet as a single panel provides a quick and easy way to accomplish this task, this implementation does not include resource management and system security. Using the AppletContext and AppletStub interfaces, applications should implement efficient application level image, audio, and class caching. To offer safe and reliable network access, the implementation of a security manager is also needed.

Acknowledgments
Special thanks to the Maryland Center for Telecommunication Research (MCTR), and Sun Microsystems for the unlimited use of computer resources throughout this project. Finally, I would like to thank Orsi Lazar for her generous help in editing the early versions of this paper.

Related Publications

  1. Sashi Lazar, "Writing Java Applications for Dynamic Content Handling". Java Developer's Journal, May 1995.
  2. Ed Tittlel and Mark Gaither, 60 Minute Guide to Java. Internet World. IDG Books Worldwide, Inc. 1995.
  3. Laura Lemay and Charles L. Perkins, Teach yourself Java in 21 Days. Sams Net Publishing, 1996.
  4. Sashi Lazar, "Building AWT Applications using Java". Independent research paper, Department of Computer Science, University of Maryland Baltimore County. March 1996.
  5. Sun Microsystems, "The Java Language Specification". Sun Microsystems, product manual included in JDK version 1.0. Sun Microsystems 1995.
  6. James Gosling and Henry McGilton. "The Java Language Overview: A White Paper". Sun Microsystems Technical Report, May 1996.
About the Authors
Sashi Lazar is working on his Ph.D. in Computer Science at the University of Maryland, Baltimore County. He is currently with the Maryland Center for Telecommunication Research sponsored by Sun Microsystems. His work is tightly coupled with two other related topics: Internet security and agent based knowledge retrieval. As part of his research, he is responsible for all Java applications, security, and protocol design.

Dr. Sidhu is a Professor with the Computer Science and Electrical Engineering Department of the University of Maryland Baltimore County (UMBC). He is also the Director of the Maryland Center for Telecommunications Research (MCTR) at UMBC. Dr. Sidhu received his Ph.D. degree in Computer Science and Theoretical Physics from the State University.

	

Listing 1: Loading and Instantiating the Applet

Applet applet = null;
try {
	Class c = Class.forName( appletName );
	applet = c.newInstance();
}
catch( Exception e ) {
	// handle exception here
}

Listing 2: Running the Applet Example Code

applet.hide();	// Hide the applet initally
applet.init();	// Initialize the applet
applet.start();	// Begin the execution of the applet
applet.resize( new Dimension( width , height ) );
applet.show();	// Show the applet
validate();	// Validate the layout manager

Listing 3: Overriding the handleEvent() Function

public boolean handleEvent( Event e ) {
	switch ( e.id ) {
		case Event.WINDOW_ICONIFY:
			applet.stop();
			break;
		case Event.WINDOW_DEICONIFY:
			applet.start();
			break;
		// Other events are handled here...
}

Listing 4: Application Level Caching

public Image getImage( URL location ) {
	Image img = cache.get(location);
	
	if ( img != null ) return img;
	img = loadImageFromURL(location);
	cache.put( location , img );

	return img;
}

Listing 5: Passing Parameters from the Application to Embedded Applets

public class Application extends Frame implements AppletStub {
	private Hashtable params = new Hashtable();

	public String getParameter( String key ) {
		return params.get(key);
	}

	public static void main( String args[] ) {
		for ( int I=0; I< args.length; I++ ) {
			params.put(getArgKey(args[i]),
				    getArgValue(args[i]) );
		}
	// Some other code
}

 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.