Applets and Java Web Start 23 Observe due measure, for right timing is in all things the most important factor. Hesiod Painting is only a bridge linking the painter s mind with that of the viewer. Eugene Delacroix The direction in which education starts a man will determine his future in life. Plato Objectives In this chapter you ll learn: What applets are and how they re used in web pages. To observe some of Java s exciting capabilities through the JDK s demonstration applets. To write simple applets. To write a simple HyperText Markup Language (HTML) document to load an applet into an applet container and execute the applet. Applet life-cycle methods. About the sandbox security model for running downloaded code safely. What Java Web Start is and how to use it to download, install and run applets outside of the web browser.
942 Chapter 23 Applets and Java Web Start 23.1 Introduction 23.2 Sample Applets Provided with the JDK 23.3 Simple Java Applet: Drawing a String 23.3.1 Executing WelcomeApplet in the appletviewer 23.3.2 Executing an Applet in a Web Browser 23.4 Applet Life-Cycle Methods 23.5 Initialization with Method init 23.6 Sandbox Security Model 23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 23.7.1 Packaging the DrawTest Applet for UsewithJavaWebStart 23.7.2 JNLP Document for the DrawTest Applet 23.8 Wrap-Up Summary Self-Review Exercise Answers to Self-Review Exercise Exercises 23.1 Introduction [Note: This chapter is intentionally small and simple for readers who wish to study applets after reading only the book s first few chapters. We present more complex applets in Chapter 24, Multimedia: Applets and Applications, and Chapter 27, Networking. Also, the examples in this chapter require some knowledge of HTML to create a web page that loads an applet. With each example we supply sample HTML documents that you can modify for your own purposes. This chapter introduces applets Java programs that are typically embedded in HTML (HyperText Markup Language) documents also called web pages. When a Java-enabled web browser loads a web page containing an applet, the applet downloads into the browser and executes. Applet Containers The application in which an applet executes is known as the applet container.it stheapplet container s responsibility to load the applet s class(es), create an instance of the applet and manage its life cycle (which we discuss in more detail in Section 23.4). The Java Development Kit (JDK) includes one called the appletviewer for testing applets as you develop them and before you embed them in web pages. We demonstrate applets using both the appletviewer and web browsers, which execute Java applets via the Java Plug-In. Some browsers don t come with the plug-in by default. You can visit java.com to determine whether your browser is ready to execute Java applets. If not, you can click the Free Java Download button to install Java for your browser. Several popular browsers are supported. We tested our applets in Mozilla s Firefox 3.6, Microsoft s Internet Explorer 8, Google s Chrome, Opera 11 and Apple s Safari 5. Java Web Start and the Java Network Launch Protocol (JNLP) This chapter concludes with an introduction to Java Web Start and the Java Network Launch Protocol (JNLP). Together, these enable you to package your applets and applications so that they can be installed onto the user s desktop. As you ll learn in Chapter 24, Java Web Start also enables you to give the user control over whether an applet or application downloaded from the web can have limited access to resources on the local file system. For example, if you create a downloadable text-editor program in Java, users would probably want to store their documentsontheirowncomputers.
23.2 Sample Applets Provided with the JDK 943 23.2 Sample Applets Provided with the JDK Before we discuss our own applets, let s consider several demonstration applets provided with the JDK. Each sample applet comes with its source code. The demonstration programs provided with the JDK are located in a directory called demo. For Windows, the default location of the JDK 6.0 s demo directory is C:\Program Files\Java\jdk1.6.0_##\demo where _## represents the JDK update number. On UNIX/Linux, the default location is the directory in which you install the JDK followed by jdk1.6.0_##/demo for example, /usr/local/jdk1.6.0_##/demo Other platforms use a similar directory (or folder) structure. You may need to update the locations specified here to reflect your chosen installation directory and disk drive, or a different version of the JDK. The demonstration programs are also available on JDK 7. If you re using a Java development tool that does not come with the Java demos, you can download the current JDK from www.oracle.com/technetwork/java/javase/downloads/index.html. Mac OS X users should visit developer.apple.com/java for information about Java SE 6 on the Mac, or use virtualization software to run the Windows or Linux versions of Java in a virtual machine. Apple recently joined the OpenJDK project (openjdk.java.net). Eventually a Mac OS X version of the JDK for Java SE 7 will be available from this project s website. Overview of the Demonstration Applets Open a command window and use the cd command to change directories to the JDK s demo directory. The demo directory contains several subdirectories. You can list them by issuing the dir command on Windows or the ls command on UNIX/Linux/Max OS X. We discuss sample programs in the applets and jfc subdirectories. The applets directory contains demonstration applets. The jfc (Java Foundation Classes) directory contains applets and applications that demonstrate Java s powerful graphics and GUI capabilities. Change to the applets directory and list its contents to see the directory names for the demonstration applets. Figure 23.1 provides a brief description of each. If your browser supports Java, you can test an applet by opening the HTML document for it in the applet s directory. We ll demonstrate three ofthese applets byusing the appletviewer command in a command window. Example Animator ArcTest BarChart Blink CardTest Description Performs one of four separate animations. Demonstrates drawing arcs. You can interact with the applet to change attributes of the arc that s displayed. Draws a simple bar chart. Displays blinking text in different colors. Demonstrates several GUI components and layouts. Fig. 23.1 The examples from the applets directory. (Part 1 of 2.)
944 Chapter 23 Applets and Java Web Start Example Description Clock Draws a clock with rotating hands, the current date and the current time. The clock updates once per second. DitherTest Demonstrates drawing with a graphics technique known as dithering that allows gradual transformation from one color to another. DrawTest Allows the user to draw lines and points in different colors by dragging the mouse. Fractal Draws a fractal. Fractals typically require complex calculations to determine how they re displayed. We discuss fractals in Section 18.8. GraphicsTest Draws shapes to illustrate graphics capabilities. GraphLayout Draws a graph consisting of many nodes (represented as rectangles) connected by lines. Drag a node to see the other nodes in the graph adjust on the screen and demonstrate complex graphical interactions. JumpingBox Moves a rectangle randomly around the screen. Try to catch it by clicking it with the mouse! MoleculeViewer Presents a three-dimensional view of several chemical molecules. Drag the mouse to view the molecule from different angles. NervousText Draws text that jumps around the applet. SimpleGraph Draws a complex curve. SortDemo Compares three sorting techniques. Sorting (described in Chapter 19) arranges information in order like alphabetizing words. When you execute this example with the appletviewer, three windows appear. When you execute it in a browser, the three demos appear side by side. Click in each demo to start the sort. The sorts all operate at different speeds. SpreadSheet Demonstrates a simple spreadsheet of rows and columns. TicTacToe Allows the user to play Tic-Tac-Toe against the computer. WireFrame Draws a three-dimensional shape as a wire frame. Drag the mouse to view the shape from different angles. Fig. 23.1 The examples from the applets directory. (Part 2 of 2.) TicTacToe Applet This TicTacToe demonstration applet allows you to play Tic-Tac-Toe against the computer. Change directories to subdirectory TicTacToe, where you ll find the file example1.html that loads the applet. In the command window, type the command appletviewer example1.html and press Enter. Thisexecutesthe appletviewer appletcontainer, whichloadsthehtml document example1.html specified as its command-line argument. The appletviewer determines from the document which applet to load and executes it. Figure 23.2 shows several screen captures of playing Tic-Tac-Toe with this applet. You can open the HTML document in your browser to execute the applet in the browser. You are player X. To interact with the applet, point the mouse at the square where you want to place an X and click the mouse button. The applet plays a sound and places an X
23.2 Sample Applets Provided with the JDK 945 Fig. 23.2 TicTacToe applet sample execution. in the square if it s open. If the square is occupied, this is an invalid move, and the applet plays a different sound, indicating that you cannot make the specified move. After you make a valid move, the applet responds by making its own move. To play again, click the appletviewer s Applet menuandselectthereload menu item (Fig. 23.3), or click the applet again when the game is over. To terminate the appletviewer, click the appletviewer s Applet menu and select the Quit menu item. Reload the applet to execute it again Select Quit to terminate the appletviewer Fig. 23.3 Applet menu in the appletviewer. DrawTest Applet The DrawTest applet allows you to draw lines and points in different colors. In the command window, change directories to directory applets, then to subdirectory DrawTest. You can move up the directory tree incrementally toward demo by issuing the command cd.. in the command window. The DrawTest directory contains the example1.html document that s used to execute the applet. In the command window, type the command appletviewer example1.html and press Enter. The appletviewer loads example1.html, determines from the document which applet to load and executes it. Figure 23.4 shows a screen capture after some lines and points have been drawn.
946 Chapter 23 Applets and Java Web Start Drag the mouse in the white area to draw Select the drawing color by clicking one of the radio buttons Select Lines or Points from the combo box to specify what will be drawn when you drag the mouse Fig. 23.4 DrawTest applet sample execution. By default the applet allows you to draw black lines by dragging the mouse across the applet. When you drag the mouse, the line s start point always remains in the same place anditsendpointfollowsthemousepointeraroundtheapplet.thelineisnotpermanent until you release the mouse button. Select a color by clicking one of the radio buttons at the bottom of the applet. You can select from red, green, blue, pink, orange and black. Change the shape to draw from Lines to Points by selecting Points from the combo box. To start a new drawing, select Reload from the appletviewer s Applet menu. Java2D Applet The Java2D applet demonstrates many features of the Java 2D API, which we introduced in Chapter 15. This demo can also be found at java.sun.com/products/java-media/2d/ samples/index.html. Change directories to the jfc directory in the JDK s demo directory, then change to the Java2D directory. In the command window, type the command appletviewer Java2Demo.html and press Enter. The appletviewer loads Java2Demo.html, determines from the document which applet to load and executes it. Figure 23.5 shows a screen capture of one of this applet s many demonstrations of Java s two-dimensional graphics capabilities. At the top of the applet are tabs that look like file folders in a filing cabinet. This demo provides 12 tabs, each demonstrating Java 2D API features. To change to a different part of the demo, simply click a different tab. Also, try changing the options in the upper-right corner of the applet. Some of these affect the speed with which the applet draws the graphics. For example, click the checkbox to the left of the word Anti-Aliasing to turn off
23.3 Simple Java Applet: Drawing a String 947 Click a tab to select a two-dimensional graphics demo Try changing the options to see their effect on the demonstration Fig. 23.5 Java2D applet sample execution. antialiasing (a graphics technique for producing smoother on-screen graphics in which the edges are blurred). Shapes that are not antialiased are less complex to draw. Accordingly, when the antialiasing feature is turned off, the animation speed increases for the animated shapes at the bottom of the demo (Fig. 23.5). 23.3 Simple Java Applet: Drawing a String Every Java applet is a graphical user interface on which you can place GUI components using the techniques introduced in Chapter 14 or draw using the techniques demonstrated in Chapter 15. In this chapter, we ll demonstrate drawing on an applet. Examples in Chapters 24 and 27 demonstrate building an applet s graphical user interface. Now let s build an applet of our own. We begin with a simple applet (Fig. 23.6) that draws "Welcome to Java Programming!" on the applet. We show this applet executing in two applet containers the appletviewer and the Mozilla Firefox web browser. At the end of this section, you ll learn how to execute the applet in a web browser.
948 Chapter 23 Applets and Java Web Start 1 // Fig. 23.6: WelcomeApplet.java 2 // Applet that draws a String. 3 import java.awt.graphics; // program uses class Graphics 4 import javax.swing.japplet; // program uses class JApplet 5 6 public class WelcomeApplet extends JApplet 7 { 8 9 10 11 12 13 14 15 16 } // end method paint 17 } // end class WelcomeApplet // draw text on applet s background public void paint( Graphics g ) { // call superclass version of method paint super.paint( g ); // draw a String at x-coordinate 25 and y-coordinate 25 g.drawstring( "Welcome to Java Programming!", 25, 25 ); Upper-left corner of drawing area is location (0, 0). Drawing area extends from below the Applet menu to above the status bar. x- coordinates increase from left to right. y-coordinates increase from top to bottom. y-axis WelcomeApplet executing in the appletviewer x-axis Pixel coordinate (25, 25) at which the string is displayed Applet menu Status bar mimics what would be displayed in the browser s status bar as the applet loads and begins executing WelcomeApplet executing in Mozilla Firefox Upper-left corner of drawing area Pixel coordinate (25, 25) Fig. 23.6 Applet that draws a String. Creating the Applet Class Line 3 imports class Graphics to enable the applet to draw graphics, such as lines, rectangles, ovals and strings of characters. Class JApplet (imported at line 4) from package javax.swing is used to create applets. As with applications, every Java applet contains at least one public class declaration. An applet container can create only objects of classes that are public and extend JApplet (or its superclass Applet). For this reason, class WelcomeApplet (lines 6 17) extends JApplet.
23.3 Simple Java Applet: Drawing a String 949 An applet container expects every Java applet to have methods named init, start, paint, stop and destroy,eachof whichis declaredin class JApplet.Eachnew applet class you create inherits default implementations of these methods from class JApplet. These methods can be overridden (redefined) to perform tasks that are specific to your applet. Section 23.4 discusses each method in more detail. When an applet container loads class WelcomeApplet, the container creates a WelcomeApplet object, then calls its methods init, start and paint in sequence. If you do not declare these methods in your applet, the applet container calls the inherited versions. The superclass methods init and start have empty bodies, so they do not perform any tasks. The superclass method paint does not draw anything on the applet. You might wonder why it s necessary to inherit methods init, start and paint if their default implementations do not perform tasks. Some applets do not use all three of these methods. However, the applet container does not know that. Thus, it expects every applet to have these methods, so that it can provide a consistent start-up sequence. This is similar to applications always starting execution with main. Inheriting the default versions of these methods guarantees that the applet container can execute each applet uniformly. Also, inheriting default implementations of these methods allows you to concentrate on defining only the methods required for a particular applet. Overriding Method paint for Drawing To enable our applet to draw, class WelcomeApplet overrides method paint (lines 9 16) by placing statements in the body of paint that draw a message on the screen. Method paint receives a parameter of type Graphics (called g by convention), which is used to draw graphics on the applet. You do not call method paint explicitly in an applet. Rather, the applet container calls paint to tell the applet when to draw, and the applet container is responsible for passing a Graphics object as an argument. Line 12 calls the superclass version of method paint that was inheritedfrom JApplet. This should be the first statement in every applet s paint method. Omitting it can cause subtle drawing errors in applets that combine drawing and GUI components. Line 15 uses Graphics method drawstring to draw Welcome to Java Programming! on the applet. The method receives as arguments the String to draw and the x-y coordinates at which the bottom-left corner of the String should appear in the drawing area. When line 15 executes, it draws the String on the applet at the coordinates 25 and 25. 23.3.1 Executing WelcomeApplet in the appletviewer After creating class WelcomeApplet and saving it in the file WelcomeApplet.java, opena command window, change to the directory in which you saved the applet class declaration and compile class WelcomeApplet. Recall that applets are embedded in web pages for execution in an applet container (appletviewer or a browser). Before you can execute the applet, you must create an HTMLdocumentthatspecifieswhichappletto execute in the applet container. Typically, an HTML document ends with an.html or.htm file-name extension. Figure 23.7shows a simple HTML document WelcomeApplet.html that loads the applet defined in Fig. 23.6 into an applet container. Most HTML elements are delimited by pairs of tags e.g., lines 1 and 6 delimit the HTML document s beginning and end, respectively. Each tag isenclosed in anglebrackets
950 Chapter 23 Applets and Java Web Start 1 <html> 2 <body> 3 <applet code = "WelcomeApplet.class" width = "300" height = "45"> 4 </applet> 5 </body> 6 </html> Fig. 23.7 WelcomeApplet.html loads WelcomeApplet (Fig. 23.6) into an applet container. (< and >). Lines 2 5 specify the body element element of the document this represents the elements that will be displayed in the web page. Lines 3 4 specify an applet element that tells the applet container to load a specific applet and defines the size of its display area (its width and height in pixels) in the applet container. The applet and its corresponding HTML document are normally stored in the same directory on disk. Typically, a browser loads an HTML document from a computer (other than your own) connected to the Internet. However, HTML documents also can reside on your computer (as in Section 23.2). When an applet container encounters an applet element in an HTML document, it loads the applet s.class file (or files) from the same location that contains the HTML document. The applet element has several attributes. The first attribute in line 3, code = "WelcomeApplet.class", indicates that the file WelcomeApplet.class contains the compiled applet class. The second and third attributes in line 3 indicate the width (300) and the height (45) of the applet in pixels. The </applet> tag (line 4) terminates the applet element that began at line 2. The </html> tag (line 6) terminates the HTML document. Common Programming Error 23.1 Forgetting the ending </applet> tag prevents the applet from executing in some applet containers. The appletviewer terminateswithoutindicatinganerror. Somewebbrowsers simply ignore the incomplete applet element. Error-Prevention Tip 23.1 If you receive a MissingResourceException error message when loading an applet into the appletviewer or a browser, check the <applet> tag in the HTML document carefully for syntax errors, such as commas (,) between the attributes. The appletviewer understands only the <applet> and </applet> HTML tags and ignores all other tags in the document. The appletviewer is an ideal place to test an applet and ensure that it executes properly. Once the applet s execution is verified, you can add its HTML tags to a web page that others can view in their web browsers. To execute WelcomeApplet in the appletviewer, open a command window, change to the directory containing your applet and HTML document, then type appletviewer WelcomeApplet.html Error-Prevention Tip 23.2 Test your applets in the appletviewer before executing them in a web browser. Browsers often save a copy of an applet in memory until all the browser s windows are closed. If you change an applet, recompile it, then reload it in your browser, the browser may still execute the original version of the applet.
23.4 Applet Life-Cycle Methods 951 Error-Prevention Tip 23.3 Test your applets in every web browser in which they ll execute to ensure that they operate correctly. 23.3.2 Executing an Applet in a Web Browser The sample program executions in Fig. 23.6 demonstrate WelcomeApplet executing in the appletviewer and in the Mozilla Firefox web browser. To execute an applet in Firefox, perform the following steps: 1. Select Open File from the File menu. 2. In the dialog box that appears, locate the directory containing the HTML document for the applet you wish to execute. 3. Select the HTML document. 4. Click the Open button. The steps for executing applets in other web browsers are similar. In most browsers, you can simply type <Ctrl> O to open a dialog that enables you to select an HTML document from your local computer. Error-Prevention Tip 23.4 If your applet executes in the appletviewer but not in your web browser, Java may not be installed and configured for your browser. In this case, visit the website java.com and click the Free Java Download button to install Java for your browser. 23.4 Applet Life-Cycle Methods Now that you ve created an applet, let s consider the five applet methods that are called by the applet container from the time the applet is loaded into the browser to the time it s terminated by the browser. These methods correspondtovarious aspects ofanapplet s life cycle. Figure 23.8 lists these methods, which are inherited into your applet classes from class JApplet. The table specifies when each method gets called and explains its purpose. Other than method paint, these methods have empty bodies by default. If you d like to declare any of them in your applets and have the applet container call them, you must use the method headers shown in Fig. 23.8. Method Description public void init() Called once by the applet container when an applet is loaded for execution. This method initializes an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 24) and creating threads (see Chapter 26). Fig. 23.8 JApplet life-cycle methods that are called by an applet container during an applet s execution. (Part 1 of 2.)
952 Chapter 23 Applets and Java Web Start Method Description public void start() Called by the applet container after method init completes execution. In addition, if the user browses to another website and later returns to the applet s HTML page, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the applet s HTML page is revisited. Actions performed here might include starting an animation or starting other threads of execution. public void paint( Graphics g ) public void stop() Called by the applet container after methods init and start. Methodpaint is also called when the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers it, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that s passed to the paint method by the applet container. This method is called by the applet container when the user leaves the applet s web page by browsing to another web page. Since it s possible that the user might return to the web page containing the applet, method stop performs tasks that might be required to suspend the applet s execution, so that the applet does not use computer processing time when it s not displayed on the screen. Typical actions performed here would stop the execution of animations and threads. public void destroy() This method is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows and may also occur at the browser s discretion when the user has browsed to other web pages. The method performs any tasks that are required to clean up resources allocated to the applet. Fig. 23.8 JApplet life-cycle methods that are called by an applet container during an applet s execution. (Part 2 of 2.) Common Programming Error 23.2 Declaring methods init, start, paint, stop or destroy with method headers that differ from those shown in Fig. 23.8 results in methods that will not be called by the applet container. The code specified in your versions of the methods will not execute. The @Override annotation can be applied to each method to prevent this problem. 23.5 Initialization with Method init Our next applet (Fig. 23.9) computes the sum of two values entered into input dialogs by the user and displays the result by drawing a String inside a rectangle on the applet. The sum is stored in an instance variable of the AdditionApplet class, so it can be used in both the init method and the paint method. The HTML document that you can use to load this applet into an applet container (i.e., the appletviewer or a web browser) is shown in Fig. 23.10.
23.5 Initialization with Method init 953 1 // Fig. 23.9: AdditionApplet.java 2 // Applet that adds two double values entered via input dialogs. 3 import java.awt.graphics; // program uses class Graphics 4 import javax.swing.japplet; // program uses class JApplet 5 import javax.swing.joptionpane; // program uses class JOptionPane 6 7 public class AdditionApplet extends JApplet 8 { 9 private double sum; // sum of values entered by user 10 11 // initialize applet by obtaining values from user 12 public void init() 13 { 14 // obtain first number from user 15 String firstnumber = JOptionPane.showInputDialog( 16 "Enter first floating-point value" ); 17 18 // obtain second number from user 19 String secondnumber = JOptionPane.showInputDialog( 20 "Enter second floating-point value" ); 21 22 // convert numbers from type String to type double 23 double number1 = Double.parseDouble( firstnumber ); 24 double number2 = Double.parseDouble( secondnumber ); 25 26 sum = number1 + number2; // add numbers 27 } // end method init 28 29 // draw results in a rectangle on applet s background 30 public void paint( Graphics g ) 31 { 32 super.paint( g ); // call superclass version of method paint 33 34 // draw rectangle starting from (15, 10) that is 270 35 // pixels wide and 20 pixels tall 36 g.drawrect( 15, 10, 270, 20 ); 37 38 // draw results as a String at (25, 25) 39 40 } // end method paint 41 } // end class AdditionApplet g.drawstring( "The sum is " + sum, 25, 25 ); Fig. 23.9 Applet that adds two double values entered via input dialogs. (Part 1 of 2.)
954 Chapter 23 Applets and Java Web Start Fig. 23.9 Applet that adds two double values entered via input dialogs. (Part 2 of 2.) 1 <html> 2 <body> 3 <applet code = "AdditionApplet.class" width = "300" height = "50"> 4 </applet> 5 </body> 6 </html> Fig. 23.10 AdditionApplet.html loads class AdditionApplet of Fig. 23.9 into an applet container. The applet requests that the user enter two floating-point numbers. In Fig. 23.9, line 9 declares instance variable sum of type double. The applet contains two methods init (lines 12 27) and paint (lines 30 40). When an applet container loads this applet, the container creates an instance of class AdditionApplet and calls its init method this occurs only once during an applet s execution. Method init normally initializes the applet s fields (if they need to be initialized to values other than their defaults) and performs other tasks that should occur only once when the applet begins execution. The first line of init always appears as shown in line 12, which indicates that init is a public method that receives no arguments and returns no information when it completes. Lines 15 24 declare variables to store the values entered by the user, obtain the user input and convert the Strings entered by the user to double values. Line 26 adds the values stored in variables number1 and number2, and assigns the result to instance variable sum. At this point, the applet s init method returns program control to the applet container, which then calls the applet s start method. We did not declare start in this applet, so the one inherited from class JApplet is called here. Next, the applet container calls the applet s paint method, which draws a rectangle (line 36) where the addition result will appear. Line 39 calls the Graphics object s draw- String method to display the results. The statement concatenates the value of instance variable sum tothe String "The sum is " and displays the concatenated String. Software Engineering Observation 23.1 The only statements that should be placed in an applet s init method are those that should execute only once when the applet is initialized. 23.6 Sandbox Security Model For security reasons, it s generally considered dangerous to allow applets or any other program that you execute from a web browser to access your local computer. So, you must
23.6 Sandbox Security Model 955 decide whether you trust the source. For example, if you choose to download a new version of the Firefox web browser from Mozilla s firefox.com website, you must decide whether you trust Mozilla. After all, their installer program is going to modify your system and place the files to execute Firefox on your computer. Once it s installed, Firefox will be able to access files and other local resources. Most of what you do with your web browsers such as shopping, browsing the web and downloading software requires you to trust the sites you visit and to trust the organizations that maintain those sites. If you re not careful, a malicious downloaded program could gain control of your computer, access personal information stored there, corrupt your data and possibly even be used to attack other computers on the Internet as so often happens with computer viruses today. Preventing Malicious Applets Applets are typically downloaded from the Internet. What would happen if you downloaded a malicious applet? Consider the fact that a browser downloads and executes a Java applet automatically the user is not asked for approval. In fact, an applet typically downloads without the user s knowledge it s just another element of the web page the user happens to be visiting. The designers of Java considered this issue thoroughly, since Java was intended for use in networked environments. To combat malicious code, thejavaplatformusesa so-called sandbox security model that provides a mechanism for executing downloaded code safely. Such code executes in the sandbox and is not allowed to play outside the sandbox. By default, downloaded code cannot access local system resources, and an applet can interact only with the server from which the applet was downloaded. Digitally Signed Applets Unfortunately, executing in a sandbox makes it difficult for applets to perform useful tasks. It s possible, however, for an organization that wishes to create applets with access to the local system to obtain a security certificate (also called a digital certificate) from one of several certificate authorities (see en.wikipedia.org/wiki/certificate_authority for a list of authorities and more information about certificate authorities). The organization can then use tools provided with the JDK to digitally sign an applet that requires access to local system resources. When a user downloads a digitally signed applet, a dialog prompts the user asking whether he or she trusts the applet s source. In that dialog, the user can view the organization s security certificate and see which certificate authority issued it. If the user indicates that he/she trusts the source, only then will the applet be able to access to the local computer s resources. In the next section, we introduce Java Web Start and the Java Network Launch Protocol (JNLP). These technologies enable applets or applications to interact with the user to request access to specific local system resources. With theuser spermission, this enables Java programmers to extend the sandbox, butitdoesnot givetheirprogramsaccesstoallof the user s local resources so the sandbox principles are still in effect. For example, it would be useful for a downloadable text editor program to store the user s files in a folder on the user s computer. The text editor can prompt the user to ask for permission to do this. If the user grants permission for a specific directory on disk, the program can then access only that local directory and its subdirectories. For more information on digitally signed applets, visit java.sun.com/developer/ onlinetraining/programming/jdcbook/signed.html. For information on the Java Plat-
956 Chapter 23 Applets and Java Web Start form security model, visit download.oracle.com/javase/6/docs/technotes/guides/ security/. 23.7 Java Web Start and the Java Network Launch Protocol (JNLP) Java Web Start is a framework for running downloaded applets and applications outside the browser. Typically, such programs are stored on a web server for access via the Internet, but theycanalsobestoredonanorganization snetworkforinternaldistribution,orevenon CDs, DVDs or other media. As you ll learn in Chapter 24, Java Web Start enables you to ask the user if a downloaded program can have access to the resources of the user s computer. Java Web Start Features Some key Java Web Start features include: Desktop integration: Users can launch robust applets and applications by clicking a hyperlink in a web page, and can quickly and easily install the programs on their computers. Java Web Start can be configured to ask the user if a desktop icon should be created so the user can launch the program directly from the desktop. Downloaded programs can also have an offline mode for execution when the computer is not connected to the Internet. Automatic updating: When you execute a program via Java Web Start, the program is downloaded and cached (stored) on the user s computer. The next time the user executes that program, Java Web Start launches it from the cache. If the program has been updated since it was last launched, Java Web Start can automatically download the updates, so a user always has the most up-to-date version. This makes installing and updating software simple and seamless to the user. Draggable applets: With a small change to the applet element that invokes an applet from an HTML document, you can allow users to execute an applet in its own window by holding the Alt key and dragging the applet out of the web browser. The applet continues to execute even after the web browser closes. Java Network Launch Protocol (JNLP) A Java Network Launch Protocol (JNLP) document provides the information that Java Web Start needs in order to download and run a program. Also, you must package your program in one or more Java archive (JAR) files that contain the program s code and resources (e.g., images, media files, text files). By default, programs launched via Java Web Start execute using the sandbox security model.ifthe user givespermission, suchprogramscan access the local file system, the clipboard and other services via the JNLP APIs of package javax.jnlp. We discuss some of these features in Chapter 24. Digitally signed programs can gain greater access to the local system if the user trusts the source. 23.7.1 Packaging the DrawTest AppletforUsewithJavaWebStart Let s package the JDK s DrawTest demonstration applet (discussed in Section 23.2) so that you can execute it via Java Web Start. To do so, you must first wrap the applet s.class files and the resources it uses (if any) into a Java archive (JAR) file. In a command
23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 957 window, change tothe DrawTest directory, as you did in Section 23.2. Once in that folder, execute the following command: jar cvf DrawTest.jar *.class which creates in the current directory a JAR file named DrawTest.jar containing the applet s.class files DrawControls.class, DrawPanel.class and DrawTest.class. If the program had other resources, you d simply add the file names or the folder names in which those resources are stored to the end of the preceding command. The letters cvf are command-line options to the jar command.the c option indicates thatthe command should create a new JAR file. The v option indicates that the command should produce verbose output so you can see the list of files and directories being included in the JAR file. The f option indicates that the next argument in the command line (DrawTest.jar) isthenew JAR file s name. Figure 23.11 shows the preceding command s verbose output, which shows the files that were placed into the JAR. added manifest adding: DrawControls.class(in = 2611) (out= 1488)(deflated 43%) adding: DrawPanel.class(in = 2703) (out= 1406)(deflated 47%) adding: DrawTest.class(in = 1170) (out= 706)(deflated 39%) Fig. 23.11 Output of the jar command. 23.7.2 JNLP Document for the DrawTest Applet Next, you must create a JNLP document that describes the contents of the JAR file and specifies which file in the JAR is the so-called main-class that begins the program s execution. For an applet, the main-class is the one that extends JApplet (i.e., DrawTest in this example). For an application, the main-class is the one that contains the main method. A basic JNLP document for the DrawTest applet is shown in Fig. 23.12. We describe this document s elements momentarily. 1 <?xml version="1.0" encoding="utf-8"?> 2 <jnlp 3 4 codebase=pathtojnlpfile href="drawtest.jnlp" > 5 6 <information> 7 <title>drawtest Applet</title> 8 <vendor>oracle Corporation</vendor> 9 <shortcut> 10 <desktop/> 11 </shortcut> 12 <offline-allowed/> 13 </information> 14 15 <resources> 16 <java version="1.6+"/> 17 <jar href="drawtest.jar" main="true"/> 18 </resources> Fig. 23.12 DrawTest.jnlp document for launching the DrawTest applet. (Part 1 of 2.)
958 Chapter 23 Applets and Java Web Start 19 20 <applet-desc 21 name="drawtest" 22 23 main-class="drawtest" width="400" 24 height="400"> 25 </applet-desc> 26 </jnlp> Fig. 23.12 DrawTest.jnlp document for launching the DrawTest applet. (Part 2 of 2.) Overview of XML JNLP documents are written in Extensible Markup Language (XML) a widely supported standard for describing data. XML is commonly used to exchange data between applications over the Internet, and many applications now use XML to specify configuration information as well as is the case with JNLP documents for Java Web Start. XML permits you to create markup for virtually any type of information. This enables you to create entirely new markup languages for describing any type of data, such as mathematical formulas, software-configuration instructions, chemical molecular structures, music, news, recipes and financial reports. XML describes data in a way that both humans and computers can understand. JNLP is a so-called XML vocabulary that describes the information Java Web Start needs to launch a program. XML documents contain elements that specify the document s structure, such as title (line 7), and text that represents content (i.e., data), such as DrawTest Applet (line 7). XML documents delimit elements with start tags and end tags. A start tag consists of the element name in angle brackets (e.g., <title> and <vendor> in lines 7 and 8). Start tags may also contain attributes of the form name=value for example, the jnlp start tag contains the attribute href="drawtest.jnlp". An end tag consists of the element name preceded by a forward slash (/) in angle brackets (e.g., </title> and </vendor> in lines 7 and 8). An element s start and end tags enclose text that represents a piece of data (e.g., the vendor of the program Oracle Corporation in line 8, which is enclosed by the <vendor> start tag and </vendor> end tag) or other elements (e.g., the title, vendor, shortcut and offline-allowed elements in the information element of lines 6 13). Every XML document must have exactly one root element that contains all the other elements. In Fig. 23.12, the jnlp element (lines 2 26) is the root element. JNLP Document: jnlp Element The jnlp element s start tag (lines 2 4) has two attributes codebase and href. The codebase attribute s value is a URL that specifies the path where the JNLP document and the JAR file are stored this is specified in Fig. 23.12 as PathToJNLPFile, since this value depends on the location from which the applet is loaded. The href attribute specifies the JNLP file that launches the program. We saved the JNLP file and the JAR file in the Draw- Test demonstration applet s directory within the JDK s directory structure. We used the following local file system URL as the codebase: file:. which indicates that the code is in the current directory (.). Typically, the codebase references a directory on a web server with an http:// URL. If you d like to serve your applet
23.7 Java Web Start and the Java Network Launch Protocol (JNLP) 959 or application from a web server so users can access it online, you ll need to configure your web server correctly, as described at java.sun.com/javase/6/docs/technotes/guides/ javaws/developersguide/setup.html. JNLP Document: information Element The information element (lines 6 13) provides details about the program. The title element specifies a title for the program. The vendor element specifies who created the program. The values of these elements appear in Java Web Start s security warnings and errors that are presented to the user. The title s value also appears in the title bar of the window in which the program executes. The desktop element that s nested in the shortcut element (lines 9 11) tells Java Web Start to ask whether the user wishes to install a desktop shortcut. If the user accepts, an icon will appear on the desktop. The user can then launch the program in its own window by double-clicking the desktop icon. Note the syntax of the <desktop/> element a so-called empty XML element. When nothing appears between an element s start and end tags, the element can be written using one tag that ends with />. The offline-allowed element (line 12) indicates that once the program is installed on the user s computer, it can be launched via Java Web Start even when the computer is not connected to the Internet. This is particularly useful for any program that can be used with files stored on the user s computer. JNLP Document: resources Element The resources element (lines 15 18) contains two nested elements. The java element lists the minimum version of Java required to execute the program (line 16) and the jar element (line 17) specifies the location of the JAR file that contains the program and whether that JAR file contains the class that launches the program. There can be multiple jar elements, as you ll see in the next chapter. JNLP Document: applet-desc Element The applet-desc element (lines 20 25) is similar to the applet element in HTML. The name attribute specifies the applet s name. The main-class attribute specifies the main applet class (the one that extends JApplet). The width and height attributes specify the width and height in pixels, respectively, of the window in which the applet will execute. Chapter 24 discusses a similar element for applications application-desc. Launching the Applet with Java Web Start You re now ready to launch the applet via Java Web Start. There are several ways to do this. You can use the javaws command in a command window from the folder that contains the JNLP document, as in javaws DrawTest.jnlp You can also use your operating system s file manager to locate the JNLP on your computer and double click its file name. Normally, the JNLP file is referenced from a web page via a hyperlink. The DrawTestWebPage.html document in Fig. 23.13 (which was saved in the same directory as the JNLP file) contains an anchor (a) element (line 4), which links to the DrawTest.jnlp file. Clicking this hyperlink in the web page downloads the JNLP file (in this case, it s loaded from the local file system) and executes the corresponding applet.
960 Chapter 23 Applets and Java Web Start 1 <html> 2 <head><title>drawtest Launcher Page</title></head> 3 <body> 4 <a href="drawtest.jnlp">launch DrawTest via Java Web Start</a> 5 </body> 6 </html> hyperlink to DrawTest.jnlp Fig. 23.13 HTML document that launches the DrawTest applet when the user clicks the link. When you run the applet via Java Web Start the first time, you ll be presented with the dialog in Fig. 23.14. This dialog enables the user to decide if a desktop icon will be installed. If the user clicks OK, a new icon labeled with the title specified in the JNLP document appears on the user s desktop. The applet is also cached for future use. After the user clicks OK or Skip in this dialog, the program executes (Fig. 23.15). Fig. 23.14 Dialog asking whether the user wishes to install a desktop shortcut. Viewing the Installed Java Web Start Programs You can view the installed Java Web Start programs in the Java Cache Viewer by typing the following command in a command window: javaws -viewer This displays the window in Fig. 23.16. The Java Cache Viewer enables you to manage the Java Web Start programs on your system. You can run a selected program, create a desktop shortcut for a program (if there isn t one already), delete installed programs, and more. For more information on Java Web Start, visit download.oracle.com/javase/6/ docs/technotes/guides/javaws/. ThissiteprovidesanoverviewofJavaWebStartand includes links to the Developer s Guide, an FAQ, the JNLP Specification and the API documentation for the javax.jnlp package.
i 23.8 Wrap-Up 961 Fig. 23.15 DrawTest applet running with Java Web Start. Run the selected application Create desktop shortcut Remove selected items Fig. 23.16 Viewing installed Java Web Start programs in the Java Cache Viewer. 23.8 Wrap-Up In this chapter, you learned the fundamentals of Java applets and Java Web Start. You leaned HTML concepts for embedding an applet in a web page and executing it in an applet container such as the appletviewer or a web browser. You learned the five methods that are called automatically by the applet container during an applet s life cycle. We discussedjava ssandboxsecurity model for executing downloaded code. Then we introduced Java Web Start and the Java Network Launch Protocol (JNLP). You packaged a program into a JAR file so that it could be executed via Java Web Start. We also discussed the basic elements of a JNLP document. Next, you ll see additional applets as we present basic multimedia capabilities. You ll also learn more features of Java Web Start and JNLP.
962 Chapter 23 Applets and Java Web Start Summary Section 23.1 Introduction Applets (p. 942) are Java programs that are typically embedded in HTML (Extensible Hyper- Text Markup Language) documents also called web pages. When a Java-enabled web browser loads a web page containing an applet, the applet downloads into the browser and executes. The application in which an applet executes is known as the applet container (p. 942). It s the applet container s responsibility toload the applet s class(es), create an instance of the applet and manage its life cycle. The JDK includes an applet container called the appletviewer (p. 942) for testing applets as you develop them and before you embed them in web pages. Web browsers execute Java applets via the Java Plug-In (p. 942). Section 23.2 Sample Applets Provided with the JDK To re-execute an applet in the appletviewer, clicktheappletviewer s Applet menu and select the Reload menu item. To terminate the appletviewer, selectquit from the appletviewer s Applet menu. Section 23.3 Simple Java Applet: Drawing a String Every Java applet is a graphical user interface on which you can place GUI components or draw. Class JApplet (p. 948) from package javax.swing is used to create applets. An appletcontainer can create only objects of classesthat are public andextend JApplet (or the Applet class from early versions of Java). An applet container expects every Java applet to have methods named init, start, paint, stop and destroy (p. 949), each of which is declared in class JApplet. Each new applet class you create inherits default implementations of these methods from class JApplet. When an applet container loads an applet, it creates an object of the applet s type, then calls the applet s init, start and paint methods. Toenable anapplet todraw, override its paint method (p. 949). The applet container calls paint to tell the applet when to draw. The first statement in method paint should be a call to the superclass method paint. Before you can execute an applet, you must create an HTML (Extensible HyperText Markup Language) document that specifies which applet to execute in the applet container. Typically, an HTML document ends with an.html or.htm file-name extension. An applet element tells the applet container to load a specific applet and defines the size of its display area (its width and height in pixels) in the applet container. Normally, an applet and its corresponding HTML document are stored in the same directory. When an applet container encounters an HTML document that contains an applet, the container automatically loads the applet s.class file(s) from the same location as the HTML document. The appletviewer understands only the <applet> and </applet> HTML tags (p. 950) and ignores all other tags in the document. Section 23.4 Applet Life-Cycle Methods Method init (p. 949) is called once by the applet container to initialize an applet when it s loaded. Method start (p. 949) is called by the applet container after method init completes execution. In addition, if the user browses to another website and later returns to the applet s HTML page, method start is called again. Method paint is called by the applet container after methods init and start.
Summary 963 Method stop (p. 949) is called by the applet container when the user leaves the applet s web page by browsing to another web page. Method destroy (p. 949) is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows and may also occur at the browser s discretion when the user has browsed to other web pages. Section 23.5 Initialization with Method init Graphics method drawstring draws a String at a specified location. Graphics method drawrect draws a rectangle at the specified upper-left corner, width and height. Section 23.6 Sandbox Security Model A browser downloads an applet without the user s knowledge it s just another element of the web page the user happens to be visiting. To combat malicious code, the Java platform uses a sandbox security model (p. 955) that provides a mechanism for executing downloaded code safely. Downloaded code cannot access local system resources, and an applet can interact only with the server from which it was downloaded. You can digitally sign an applet that requires access to local system resources. If the user indicates that he/she trusts the applet s source, only then will the applet be able to access the local computer s resources. Section 23.7 Java Web Start and the Java Network Launch Protocol (JNLP) Java Web Start (p. 956) is a framework for running downloaded programs outside the browser. Users can launch robust applets and applications by clicking a hyperlink in a web page, and can quickly and easily install the programs on their computers. Java Web Start can be configured to ask the user if a desktop icon should be created so the user can launch the program directly from the desktop. Downloaded programs can also have an offline mode for execution when the computer is not connected to the Internet. When you execute a program via Java Web Start, the program is downloaded and cached (stored) on the user s computer. The next time the user executes that program, Java Web Start launches it from the cache. If the program has been updated since it was last lauched, Java Web Start can automatically download the new version, so a user always has the most up-to-date version. A Java Network Launch Protocol (JNLP; p. 956) document provides the information that Java Web Start needs to download and run a program. Programs launched via Java Web Start execute using the sandbox security model. The user can permit access to the local file system, the clipboard and other services via the JNLP APIs. Section 23.7.1 Packaging the DrawTest Applet for Use with Java Web Start The jar command (p. 957) is used to create JAR files. Option c indicates that the command should create a new JAR file (p. 957). Option v indicates that the command should produce verbose output (p. 957). Option f indicates that the next argument in the command line is the new JAR file s name (p. 957). Section 23.7.2 JNLP Document for the DrawTest Applet A JNLP document describes the contents of the JAR file and specifies which file in the JAR is the so-called main-class (p. 957) that begins the program s execution. JNLP documents are written in Extensible Markup Language (XML) a widely supported standard for describing data (p. 957).
964 Chapter 23 Applets and Java Web Start JNLP is a so-called XML vocabulary that describes the information Java Web Start needs to launch a program. The jnlp element s (p. 958) codebase attribute specifies the path wherethejnlpdocumentand the JAR file are stored. The href attribute specifies the JNLP file that launches the program. Typically, the codebase references a directory on a web server with an http:// URL. The information element (p. 959) provides details about the program. The title element (p. 959) specifies a title for the program. The vendor element (p. 959) specifies who created the program. The desktop element nested in the shortcut element (p. 959) tells Java Web Start to ask users whether they wish to install a desktop shortcut. The offline-allowed (p. 959) element indicates that a program can be launched via Java Web Start even when the computer is not connected to the Internet. The resources element (p. 959) contains a java element (p. 959) that lists theminimum version of Java required to execute the program and a jar element (p. 959) that specifies the location of the JAR file. The applet-desc (p. 959) element s name attribute specifies the applet s name. The main-class attribute specifies the main applet class. The width and height (p. 950) attributes specify the width and height in pixels, respectively, of the window in which the applet will execute. To launch the applet via Java Web Start you can use the javaws command (p. 959). You can also use your operating system s file manager to locate the JNLP on your computer and double click its file name. Normally, a JNLP file is referenced from a web page via a hyperlink. WhenyourunanappletviaJavaWebStartthefirsttimeandtheJNLPdocumentspecifiesthat a desktop icon should be installed, you ll be presented with a dialog that enables you to decide whether to install the desktop icon. If you click OK, a new icon labeled with the title specified in the JNLP document appears on the desktop. You can view the installed Java Web Start programs in the Java Cache Viewer by typing the command javaws -viewer in a command window. TheJava Cache Viewer enables you to manage the installed Java Web Start programs. You can run a selected program, create a desktop shortcut, delete installed programs, and more. Self-Review Exercise 23.1 Fill in the blanks in each of the following: a) Java applets begin execution with a series of three method calls:, and. b) The method is invoked for an applet each time a browser s user leaves an HTML page on which the applet resides. c) Every applet should extend class. d) The or a browser can be used to execute a Java applet. e) The method is called each time the user of a browser revisits the HTML page on which an applet resides. f) To load an applet into a browser, you must first define a(n) file. g) Method is called once when an applet begins execution. h) Method is invoked to draw on an applet. i) Method is invoked for an applet when the browser removes it from memory. j) The and HTML tags specify that an applet should be loaded into an applet container and executed.
Answers to Self-Review Exercise 965 k) is a framework for running downloaded programs outside the browser. l) A(n) document provides the information that Java Web Start needs to download and run a program. m) The enables you to manage the Java Web Start programs on your system. Answers to Self-Review Exercise 23.1 a) init, start, paint. b) stop. c) JApplet (or Applet). d) appletviewer. e) start. f) HTML. g) init. h)paint. i)destroy. j)<applet>, </applet>. k) Java Web Start. l) Java Network Launch Protocol (JNLP). m) Java Cache Viewer. Exercises 23.2 (Arithmetic) Write an applet that asks the user to enter two floating-point numbers, obtains the two numbers from the user and draws their sum, product (multiplication), difference and quotient (division). Use the techniques shown in Fig. 23.9. 23.3 (Comparing Numbers) Write an applet that asks the user to enter two floating-point numbers, obtains the numbers from the user and displays the two numbers, then displays the larger number followed by the words "is larger" as a string on the applet. If the numbers are equal, the applet should print the message "These numbers are equal." Use the techniques shown in Fig. 23.9. 23.4 (Arithmetic and Numeric Comparisons) Write an applet that inputs three floating-point numbers from the user and displays the sum, average, product, smallest and largest of these numbers as strings on the applet. Use the techniques shown in Fig. 23.9. 23.5 (Diameter, Circumference and Area of a Circle) Write an applet that asks the user to input the radius of a circle as a floating-point number and draws the circle s diameter, circumference and area. Use the value 3.14159 for π. Use the techniques shown in Fig. 23.9. [Note: You may also use the predefined constant Math.PI for the value of π. This constant is more precise than the value 3.14159. Class Math is defined in the java.lang package, so you do not need to import it.] Use the following formulas (r is the radius): diameter =2r circumference =2πr area = πr 2 23.6 (Largest and Smallest) Write an applet that reads five integers, determines which are the largest and smallest integers in the group and prints them. Draw the results on the applet. 23.7 (Draw a Checkerboard Pattern) Write an applet that draws a checkerboard pattern as follows: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 23.8 (Drawing Rectangles) Write an applet that draws rectangles of different sizes and locations. 23.9 (Drawing Rectangles Based on User Input) Write an applet that allows the user to input values for the arguments required by method drawrect, then draws a rectangle using the four input values.
966 Chapter 23 Applets and Java Web Start 23.10 (Drawing Ovals and Rectangles) Class Graphics contains method drawoval,whichtakesas arguments the same four arguments as method drawrect. TheargumentsformethoddrawOval specify the bounding box for the oval the sides of the bounding box are the boundaries of the oval. Write a Java applet that draws an oval and a rectangle with the same four arguments. The oval will touch the rectangle at the center of each side. 23.11 (Drawing Ovals and Rectangles) Modify the solution to Exercise 23.10 to output ovals of different shapes and sizes. 23.12 (Drawing Ovals Based on User Input) Write an applet that allows the user to input the four arguments required by method drawoval, then draws an oval using the four input values. 23.13 (TicTacToe Demonstration Applet with Java Web Start) Package the TicTacToe demonstration applet from the JDK (discussed in Section 23.2) for use with Java Web Start, then copy the JNLP document in Fig. 23.12 and modify it so that it launches the TicTacToe applet.