Welcome!

PowerBuilder Authors: Chris Pollach, Yakov Fain, RealWire News Distribution, Al Soucy, Elizabeth White

Related Topics: PowerBuilder

PowerBuilder: Article

Use Your PB Knowledge And Deploy Java Applets

Use Your PB Knowledge And Deploy Java Applets

This month we'll discuss how to build and deploy simple Java applets. By the end of this article, you should have the skill set needed to write, compile, deploy, and run simple Java applets. As you'll soon see, the coding portion of this is relatively easy. The real challenge is understanding the process, which will be my focus. Of course, I'll relate the material to the PowerBuilder knowledge you already know and love.

The goal this month is to recognize the various components involved and the role they play. After this, understanding the code is relatively straightforward.

Before starting, it's important to understand the different components and their roles in the development of applets. In the classic PowerBuilder client/server deployment model we're primarily interested in two things - creating the executable and deploying it on a computer. At this point we can map a shortcut to this file and, bada bing, the application is up and running. Writing Java applets is a bit more confusing than this. Before we can write and deploy an applet, it's important to understand the role of the four main components of applet deployment - the applet, HTML file, Web browser, and Web server.

Applet
Quite simply, an applet is a small Java program that can be executed only from within a Web browser. It's a compiled version of a Java source program and is often called a class file because of its .class file extension. The first purpose of an applet is to sit on a Web server and wait until an HTML file requests it. When a user surfs to a Web site, the user's PC (client) communicates to the Web server (server) via HTML. The HTML file exists on the server. The file is then "served" to the client where it's displayed within the client's Web browser. That's it. In this series I'll explain the details of this process and the inevitable pitfalls you may encounter. As you can see, the process is relatively simple. Also, the process doesn't vary much from one implementation to another.

HTML File
This file contains all the content. When you look into your Web browser, you're looking at the interpreted version of an HTML file. HTML files live on the Web server and are downloaded to your local computer where the Web browser interprets them and displays the results.

HTML consists of properties called tags. These tags tell the Web browser what the HTML page contains and how it looks. An HTML file can "request" an applet in one of these tags. If the HTML file learns (via a tag) that it needs to run a Java applet, the client notifies the server of the applet's name and where the server can find it. The applet is then "served" to the client where it's interpreted by the client's Web browser. The HTML file knows very little about the applet; it knows what Web server it lives on, how to ask for it, and where in the Web browser the user will see it run. The HTML file doesn't know anything about what the applet does or how it runs. HTML files don't need applets, but applets need HTML files. Applets cannot, will not, and never will be able to run without first being requested by an HTML file (I really set myself up, didn't I?). An HTML file may contain programmatic logic; however, the logic must be simple. For this reason HTML isn't considered a language.

Web Browser
This contains the HTML file and the Java applet. When an HTML page is loading within the browser, the browser asks the HTML file if it knows about any applets that need to be run. If so, the HTML file tells the Web browser the name of the applet(s) and what Web server it can be found on. The applet is downloaded to the client machine, then the Web browser interprets the HTML file and the applet and the results are displayed to the user.

Since the applet is run within the browser, Java programming with applets is often called client-side Java. There are a couple important things to point out here. First, the Web browser is the component that actually runs the applet. Many developers mistakenly say the applet runs on the client. While it's true that the applet currently exists on the local client machine, the applet isn't run on it; rather, it's run within the Web browser. So what's the difference? Plenty. By default, because of security reasons, an applet can't exist outside of the client Web browser. The browser keeps the applet insulated from the client system. The entire universe for the applet exists within the Web browser; it can't see any further. Since an applet can't see beyond the browser, it can't access the client system, including access to files, memory, printers, and the operating system.

The area the browser allows the applet to run in is called the sandbox. Like its namesake, the sandbox provides a safe place to play. Like a toddler, an applet can wreak havoc. Because the browser allows the applet to access only the sandbox, the client computer is relatively safe from destructive applets. This security feature is needed to prevent an unscrupulous programmer from unleashing harmful applets into the world. The trade-off is that this strict security model severely limits what an applet can do.

Web Server
This is a computer that responds to HTTP requests. When someone points their Web browser to a Web site, the browser talks to the server in the form of HTTP requests. The Web server responds to these requests in the form of transferring files. Typically, this computer serves HTML pages to whoever asks for them. If the HTML page contains a tag that specifies an applet, the applet is also served to the requesting client computer where it's interpreted and run within a Web browser. The Web server doesn't know anything about the content of the HTML page or the applet. All it knows is if the files exist - if they do, it serves them; if not, an error message is displayed. Web servers run a variety of operating systems such as UNIX or Microsoft Windows NT. Also, Web servers don't need any additional software to allow them to serve Java applets. Remember, the Web server's job is to transfer files, not run them.

Building the Applet
Now that you're familiar with the pieces, we're finally ready to build our first applet. Remember, Java has no development interface; it's a command line-driven language. Because of this, Java is initially developed in a text editor. Pick any ASCII test editor you wish. Because of its widespread use, I use Microsoft Notepad. The following code contains your first applet. Type it in and save it with the file name Applet1.java.

// A very simple applet
import java.awt.*;
import java.applet.*;

public class Applet1 extends Applet {
public void paint(Graphics g) {
g.drawString("I am now a web developer!", 50, 25);
} // Ends paint
} // Ends class

I won't provide an exhaustive list of Java syntax rules here, but I'll start by offering short and simple explanations and tips.
// A very simple applet

This is a comment and should look familiar. Commenting code in Java follows the same rules as commenting code in PowerBuilder. Single lines may be commented as in the foregoing. Multiple line comments must begin with a /* and end with a */, and everything between these symbols is considered comments.

import java.awt.*;
import java.applet.*;
These lines specify which Java packages are included in the program. Since Java is a big language, objects within Java are organized into so-called packages that are related classes. If you're familiar with C, the Java import statement serves the identical purpose of the C include statement. This system is similar to how you might arrange objects in different PBLs. The main difference is that Java system classes are already put in these packages, whereas in PowerBuilder it's up to you to put objects in PBL files. When appropriate, I'll explain the basic contents of Java packages as we use them. By default the java.lang package is imported and includes all the basic rules and classes of the Java language. In the previous example, the awt and applet packages are imported. The * symbol means "give me all classes in the specified package." Later you'll see how to import individual classes rather than entire packages, but that's not important here. Import statements must end with a semicolon. Also, note that Java is case sensitive, so be careful when typing.
public class Applet1 extends Applet {

This is the class declaration line. Every Java program needs one, and it must appear immediately after the import statements. The first word identifies the scope (who can use) of the class. Notice how the name (Applet1) is in uppercase. This is a Java convention, to have all classes start with an uppercase letter. Note: An important Java rule is that the name of your file must be identical to the class name. For example, I'd have to name this file Applet1.java. Any other file name wouldn't even compile. The extends portion of the class declaration specifies which class ours is inherited from. You'll be pleased to know that Java uses inheritance the same way PowerBuilder uses it. In this case we're inheriting for the Java class Applet. As in PowerBuilder, your Java class doesn't have to be inherited from anything, so the extends portion is optional. Last, the "{" symbol starts your class block and must be terminated by a "}" and the end of the program.

public void paint(Graphics g) {
g.drawString("I am now a web developer!", 50, 25);
} // Ends paint
Above is the applet paint method. This method overrides an ancestor method of the same name. Java fires this method every time the applet needs to draw itself. The method has public access and returns nothing (void), an automatic method. This may be a new experience for you. In Java, some methods are wired to automatically fire on their own. In other words, Java is responsible for firing them - not you. Java is full of automatic methods such as paint. In PowerBuilder terms these automatic methods act more like events. There are other automatic methods in the applet class, and they'll be discussed in detail next month.

The () holds the signature for the method. Java passes a graphics object to the paint method and we refer to it as g. At the end of the signature there's a "{", which starts our signature block. Similar to class blocks, signature blocks must be terminated by a "}".

Also notice the indenting. Signature blocks are indented three characters from the class block. Three additional characters indent code in a signature block. This is not a Java requirement but makes the code more readable and easier to debug. Java is space insensitive - it ignores white space.

The paint method contains only one line of code. The drawString method on the Graphics class is told to draw a string on the applet 50 pixels over and 25 pixels down. The Graphics class is used to draw text and simple shapes on the applet and will be discussed in more detail next month.

Compile the Applet
The next step is to compile the applet by downloading the JDK (Java Developer's Kit) from Sun Microsystems' Web site. The current JDK can be found at http://java.sun.com/products/jdk/1.0.2/.

Follow the downloading and installation instructions. They're simple and easy to follow so I won't waste any space discussing them. Figure 1 shows a successful compile. After the compile, a class file will be generated that will soon be deployed to a Web server.

Create the HTML File
As noted previously, for an applet to run it must first be specified within an HTML file. Use your favorite text editor to create the following HTML file listed below. Save the file as Applet1.htm and make sure you save it in the same directory as your applet.

HTML Explained
Notice the APPLET tag: it specifies three properties for the applet - the CODE tag specifies the name of the applet, and the WIDTH and HEIGHT tags specify how many corresponding pixels will be allocated for the applet to run within the HTML page. There are other properties associated with the APPLET tag, but these three are required. Unlike Java, HTML isn't case sensitive.

Testing the Applet
Are we ready to upload our applet and HTML file to a Web server? Almost. Before we take that step let's first test our creation locally. An excellent testing tool is the Java Applet Viewer and it's included in the downloaded JDK. The Applet Viewer reads an HTML file and runs the applet specified by the APPLET tag. While not a full-fledged Web browser, the Applet Viewer provides a quick way to determine if our applet is working. To run the Applet Viewer, go to the directory that contains the HTML file and applet and type:

AppletViewer Applet1.htm

This runs the applet within the HTML file. If all is well, the contents of the Applet Viewer should look like Figure 2.

Deploying to a Web Server
This is the final step. You want the world to see your first applet, right? To deploy to a Web server you must first have one available. For most people, that usually means shared Web hosting. Most Web hosting companies let you have FTP access to your account. After you send the two files to your Web server, you're all set. In the following sequence, I'll upload the two files to my Web server. Figure 3 shows the actual FTP sequence.

ftp> open ftp.envisionsoft.com
user> envi99
password> *********
ftp> send c:\jdk1.2.2\bin\Applet1.htm
ftp> binary
ftp> send c:\jdk1.2.2\bin\Applet1.class

About FTP
Almost every computer contains the FTP utility. If you're running Microsoft Windows, you can access the FTP utility simply by typing ftp at a DOS prompt. As you've probably guessed, before you're able to use FTP, an Internet connection must first be established. If you have dedicated access you already have a connection. If not, first establish a dial-up connection with your ISP (e.g., Prodigy or AOL).

The FTP Commands
After an FTP connection has been opened, the Web server prompts you for a user ID and password. If you don't know them, ask the people who host your Web site. After you're logged in, the files can be uploaded via a send command. Notice in the previous example that the transfer mode is set to binary before uploading the class file. Always send class files in binary mode. HTML files are sent in the default ascii mode. If you want a list of FTP commands (there are only a handful), type in help at the FTP prompt. Learning them takes a bit of practice, but FTP is relatively simple. You'll be a pro in no time flat.

The Final Step
Finally! The moment you've been waiting for. Now that your applet and HTML file have been deployed, you can load them in a Web browser. In the example I've been using, I need to specify the Web address followed by the HTML file I want to load. The Web browser should then load the HTML file and start running the applet. If all is working, your Web browser should be similar to Figure 4.

Final Words
Congratulations! You're now a Java developer. Of course, it gets more complicated than this, but for the most part these are the development steps you'll follow: program, compile, test, and deploy. Everything you do falls into one of these steps.

All this Java development has probably made you thirsty. Since you have a new skill, have your boss take you out for a drink. While you're at it ask for a raise. After all, you deserve one.

Next Month
Adding spice to your applet by using the Graphics class.

More Stories By Bob Hendry

Bob Hendry is a PowerBuilder instructor for Envision Software Systems and a frequent speaker at national and international PowerBuilder conferences. He specializes in PFC development and has written two books on the subject, including Programming with the PFC 6.0.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.