Chapter 13

Java and JavaScript


CONTENTS

One of the advances the Netscape corporation added to its second generation Web servers, Enterprise Server and FastTrack Server, was the ability to uniquely utilize the Java and JavaScript languages for server side work. This integration is designed to help you, more easily, perform the tasks which were previously accomplished through CGI scripts.

In this chapter, you will learn:

What this chapter will not cover:

This chapter is not designed to teach you how to write Java or JavaScript. Both of those subjects are far too large for a single chapter. If you would like to learn Java it would be a good idea to pick up another QUE book, Special Edition Using Java; for JavaScript get Special Edition Using JavaScript.

Java and JavaScript Defined

Before you start to learn about Java and JavaScript, it is important to first establish what they are. You see, it's important to establish that Java and JavaScript are at best very distant cousins. Despite what the names might suggest JavaScript is not Java 'lite' or 'Java for Beginners.' The two technologies have very diverse histories, and are quite different.

JavaScript is a language that was developed by Netscape Communications. Originally, JavaScript was developed under the name LiveScript. In November 1995, when Sun Microsystems and Netscape realized that Java was fast becoming the most hyped technology of the year, LiveScript was renamed JavaScript. Both languages are very well suited to creating dynamic Web pages. These pages can save your users time, and add a level of interaction, which was not possible before.

Java Defined

The programming language, Java was developed by Sun Microsystems. Java is roughly based on another popular programming language called C++. Actually, Sun borrowed from a great number of languages. Java has many advantages over traditional languages such as C++. The most significant of which, is that Java is not tied to one type of computer platform.

Sun's official definition for Java is:

"Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language."

That definition is more than Sun's attempt to use every buzz word they could think of. Each of the terms in the definition have a specific meaning to the language. If this book were about Java, it would be important to look at how each one of these terms relates to Java uniquely; however, that's a bit too detailed for a single chapter. For now, let's look at the two portions of this definition which are of particular interest to Web masters.

Java Is Architecture Neutral

Architecture Neutral is a complicated way to say that a Java program can run on any computer, or platform. Architecture neutrality is also known as platform independence. This is one of the main reasons why Java is the best solution for many problems on the Internet or an Intranet. Because Java is platform independent, once a Java application is created, that same application can be run without any modifications, on any computer. Well, that's not entirely true. In order for a computer to support Java, it must have support for what is known as the Java Virtual Machine (VM). Currently, there are dozens of machines which support the VM, with more on the way.

One way to visualize the power of architecture neutrality is to consider what would happen if your favorite word processor were written in Java. If that application were written in Java, the same application could be installed on a Windows 95 machine, on a Macintosh, a UNIX machine, or a Dec VAX. So, you're saying to yourself, but I do. I have Microsoft Word for Windows and Microsoft Word for Macintosh, isn't that the same thing? The answer is no. You actually have two separate and distinct programs there. If the program were written in Java, the exact same disks could be placed in both your Macintosh and your Windows machine and execute the same code.

Platform independence may or may not be important to you for server-side interaction. If you are writing a program which will run on your server, and are not planning on using it on any other system, being architecture neutral doesn't mean much. On the other hand, the odds are that if you take the time to write a server application, you will want to use it on more Web servers than your own, or even sell it. In that case, you will appreciate Java's ability to run on any UNIX machine and Windows NT. In fact, one of the reasons that Perl has become the de facto standard for CGI on the Web is that Perl's scripting language is also fairly architecture neutral.

Java Is Secure

Java was designed from the very beginning to be a secure language. What Sun meant by secure was that they did not want a programmer to be able to write a Java applet, which could harm your computer. Just imagine the havoc that could be caused by a virus written in Java which could run on any computer! Fortunately, because Sun had the foresight to see this, such attacks are not possible with Java.

Java's security is actually of more benefit to the people who view your Web pages than you as a Web master. Java's security model means that the Java applications, which are placed on the Web, can't do malicious things to your machine when it is downloaded. In a world, which is constantly fighting the computer flu (virus), it was extremely important for Sun to minimize the threat that Java applets could be used as a means to distribute such attacks. Sun also limited the applets' ability to access the local file system. This means that a Java applet can't be used to steal the information on your local hard drive.

The security model, however, does not extend to Java-based applications. This means that the Java applications that you use on your server are able to violate some of the holds on the security model. For instance, Java applications can access your local disk drive, both for reading and writing. If they could not do this, they would be of little use to you for CGI applications, but installing someone else's server-based Java application is as dangerous as any other type of CGI. The one benefit that Java's security model does still afford you, though, is that the applications are still not allowed to access the computers memory pool. They are restrained to their own working set of memory; this eliminates the ability to corrupt other running programs.

JavaScript Defined

JavaScript is a scripting language, and is actually embedded into an HTML file. Where with Java, a reference to the Java applet is added to the HTML file, with JavaScript the whole program is actually contained inside of the HTML file.

JavaScript was designed to be a complimentary language to Java and to act as middleware between Java and Plug-ins. Though there are several distinctions between the two, the syntax of JavaScript does vaguely resemble that of Java; this is primarily due to the fact that both Java and JavaScript are derived from the same source C language.

JavaScript was designed to be an easy language to learn and use. In fact, JavaScript was designed for the majority of Web designers who, understandably would rather deal with the aesthetic appearances of their Web pages than the technical details of programming. Nevertheless, to program complicated applications in JavaScript requires a bit of programming skill.

Java versus JavaScript

There are a great number of differences between Java and JavaScript beyond syntax. These differences have their pluses and their minuses.

JavaScript Is Contained in the HTML File

The source code, for a JavaScript program, is contained within the HTML file along with the other text, which is interpreted by the browser.

In the case of JavaScript, which is interpreted by the server, this embedding in HTML can be very helpful. You can, for instance, write an HTML file in much the same way as you ordinarily would, and only change the part of the page that you want to be dynamic.

JavaScript Is Interpreted

For server-side pages, Netscape extended the byte-code technology of Java to JavaScript and so the interpretation doesn't really affect purely server-side pages. These pages must pass through a special compiler which Netscape ships with their LiveWire product.

For standard Web pages, however, JavaScript is interpreted so there is no need to compile the script before it is available for use. Java, on the other hand, requires an initial compilation to occur before it can be utilized. On the flip side, this compilation does make Java a faster language.

At this point, you might be saying to yourself, "but I have heard that Java is both compiled and interpreted, how does JavaScript differ?" The answer to this question lies in the level at which Java is interpreted.

Every computer has what is known as a machine language. This language is made up entirely of ones and zeroes, and essentially turns transistors on and off. Machine language is a very complicated beast, and as such, the only people who program in it are the true gurus of this world. A very close cousin to machine language is assembly language. Assembly language converts the machine language to letters, which are more easily remembered by humans. Now, how this applies to Java is that Java has a unique pseudo-assembly language of its own. This assembly language is not a real language for a real computer; it is an abstract language for Java. When Java is compiled, it generates, more or less, to this pseudo-assembly language. When your computer downloads a Java class file, it must then convert the pseudo-assembly language to the actual assembly language of your machine. This translation is a relatively simple one. This is the level where Java's interpretation originates-interpreting the virtual machine's assembly language into the native assembly language of your computer. In addition, the interpreter also performs some work, called object-linking.

Now let's look at a typical JavaScript which might be included in standard HTML. With JavaScript, your browser downloads something that looks like listing 13.1


Listing 13.1  
<HTML>
<HEAD>
<SCRIPT>
document.write("<H1>This is a simple JavaScript demo">);
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

There is a lot there, but to be fair, the JavaScript interpreter has to only look at one line:

document.write("<H1>This is a simple JavaScript demo">);

This is a very simple line of code, but to a computer it doesn't mean anything. The JavaScript interpreter must first translate the document, write, and then figure out how to use it. With Java, much less translation is required, since most of it was done when the class file was created.

Why Use Java for Server-Side Applications

So why would you want to use Java to perform server-side interaction? Well, first, for developers, who are already working in the Java programming language and who want to take advantage of the rapid development cycles afforded by Java, server-side Java is a natural extension. Second, it's often advantageous to utilize the efforts that are put into a client-side Java applet and utilize them on the server. One prime example of where this can be extremely helpful, is with programs that serve dual purposes. Java can be used not only on the Web, but also on desktops. As a result of the unique platform independence Java provides, it is being used to develop in many situations where the medium of delivery is both CD-ROM and Internet. With Java, it is possible to deliver exactly the same application in both forms, and take advantage of the unique abilities that each medium provides. When many of these applications hit the Internet though, they suffer badly because of bandwidth restrictions. With a CD-ROM, it is menial to place and search large amounts of data, since all the data is right there on the disc. Transferring all the data across the Internet is very problematic. As a result, it would be nice to limit the data set. By extracting the search portion the applet for the server (without any other code changes), this limitation is simple and very cost effective.

In addition to these benefits, with server-side applets, there is a great power that can be derived by utilizing the client-server abilities of Java. By interacting with a client-side Java applet, a server-side applet can share the load with the client. When this situation is put into effect, you can produce the best fit solution for your environment and limit the amount of calculations performed by the server, thereby reducing your load, and at the same time limiting the amount of bandwidth which is required by the client.

Server-side Java can be done in three ways. First, using standard CGI, the program, written in Java, must actually comply with the application specification for Java, and can't become an applet. Using Java to perform standard CGI is similar to doing CGI with Perl or C. However, there is one major disadvantage to this mechanism. In order for a Java applet or application to run, a "supporting" program, known as the Java Virtual Machine, must first be loaded and run. The virtual machine actually runs the Java applet or application. The time involved for the Virtual Machine to load, while not long, is prohibitive for CGI applications where short response times are critical.

The second mechanism for running a server-side Java application is through the Netscape Server-java directory with Netscape Enterprise or LiveWire servers. These servers eliminate the need for the Virtual Machine to load by keeping it in memory at all times. In addition, Netscape has built an API, which allows server-side applets to obtain information about various states of the network in an almost rudimentary way.

The third option for doing server-side Java is through a brand new API which Sun Microsystems has announced it will be releasing. Under the new API Java, objects known as servlets, can be loaded dynamically by a Java-based server. These servlets can actually be linked into the server and extend the capabilities of the server. The server is actually able to, quickly and efficiently, interact with the power of Java.

Enabling Java on the Enterprise or FastTrack Server

In order for you to take advantage of the Java serving capabilities of the Enterprise or FastTrack servers, you must first enable these options on the server.

The controls for the Java Virtual Machine are located in the server controls. Netscape's new integrated server management system includes many controls for your server, each of these is placed under different headings. To get to the Java controls, the first thing you need to do is select the PROGRAMS file in the main window. Next, you need to select the JAVA controls in the side frame. Finally, to have the server utilize the Java Virtual machine, you must select YES and select OK.

Once you select OK, the server prompts you to confirm the changes, and to restart the server. If all goes as planned, the server should notify you that it has been restarted (as seen in figure 13.1). If not, you may need to manually stop and restart your server for these changes to take effect.

Figure 13.1 : The Server should confirm that it has restarted.

With the Netscape 2.0 servers, the directory /server-java has been set aside in much the same way that /cgi-bin has been used on first generation HTTP servers. Now that you have enabled Java on your Web server, you can confirm that it is working by utilizing some of the Java applications that are included with the Enterprise and FastTrack Servers.

NOTE
In order for you to utilize the demonstration classes, which are shipped with the Enterprise and FastTrack servers, you need to make sure you have entered the correct directory in the 'Java Applet Directory' during your server configuration. By default, this directory is /usr/ns-home/plugins/java/applets.
Change the /usr/ns-home to the directory which is appropriate for your installation.

To test the Java implementation with your server, you can now open the URL /server-java/BrowserDataApplet in your browser. This should cause the server to run the BrowserDataApplet and return information about your browser as shown in figure 13.2.

Figure 13.2 : The BrowserDataApplet reveals information about your browser.

Notice that the information that is shown about the browser is the information the browser provides to the server. There is no magic bullet here, the server must rely on what/who the Browser claims to be. As a result, if you use the information, you should be aware that a browser can provide information that may not seem to be correct. Some browsers, such as Microsoft Internet Explorer, show themselves as being Mozilla for compatibility with Netscape as shown in figure 13.3.

Figure 13.3 : Microsoft Internet Explorer claims to be Mozilla.

So where does this information come from? First, take a look at the directory:

/Netscape-server-directory/plugins/java/applets

Make sure you substitute /Netscape-server-directory for the directory in which your Netscape 2.0 server resides. In that directory, there are several files, one of which is called BrowserDataApplet.class. If you are already a Java programmer, you will recognize this as a Java class file, which is Java's equivalent to an .exe file.

When you accessed the directory /server-applets, the Enterprise server went out and loaded the BrowserDataApplet class into its interpreter and the results were sent to your browser, just like a CGI program.

Begin Developing a Java Applet

There is not enough space in this book to truly cover Java. In addition, this chapter only talks about using Java to create Server-Applets. It should be pointed out that Java can, just as easily, be used to create applications that run on local machines, or for applets that can be distributed as easily as GIF files to your Web clients.

Before you can create a Java applet, it is necessary to first download the Java Developers Kit (JDK) and install it. The JDK includes tools to compile the Java source code into Java class files, which can then be run. You can obtain the JDK from Sun Microsystems at:

http://java.sun.com/devcorner.html

NOTE
In Java, what JavaScript and many other languages call functions are called methods.

HelloWorld Java Application for a Server Applet

Before we dive into our own version of the BrowserDataApplet, let's take a look at how to do something a bit simpler. In almost every language since Kernie and Richie invented C, the first program is traditionally one that says "Hello World." Java is a unique language in that it has a number of different "Hello World" implementations depending on how it is being used. In the current situation, you want to have the server send a document which simply says "Hello World" to the browser.

Listing 13.2 shows the source code for the server-side applet Hello World program.


Listing 13.2  Hello World for Server Side Java Application
/*  Import the required classes from other packages  */
import netscape.server.applet.HttpApplet;
import java.io.PrintStream;

/*  The class which is created is called HelloWorld  */
public class HelloWorld extends HttpApplet{

  public void run() throws Exception {
     PrintStream out = getOutputStream();
     out.println ("HelloWorld");
  }
  
  }

Understanding the Source Code for the HelloWorld Application

In order to understand the source code for the HelloWorld application, let's take it line by line. The first two lines of the code import two classes. The first class is provided by Netscape and the second is included with the Java library provided with Sun's Java Developer Kit:

/*  Import the required classes from other packages  */
import netscape.server.applet.HttpApplet;
import java.io.PrintStream;

netscape.server.applet.HttpApplet is probably the most important class included with the API from Netscape. The server expects all the programs that it loads to be HttpApplet. As you will see in the next line of code, you can make the HelloWorld class into an HttpApplet by extending, or inheriting, the characteristics of HttpApplet.

The next line of code is what is known as the class declaration. In the declaration you need to declare the properties which the HelloWorld class will have. In order to be usable as a server-applet, all classes must be declared to be public (so the server can read them) and to extend HttpApplet.

/*  The class which is created is called HelloWorld  */
public class HelloWorld extends HttpApplet{

All server applets need to overload the method run(). The run method is the method that the Server will run when a user attempts to access the URL where the HelloWorld applet is located. In a certain sense, you can think of the run() method as the cousin of the main() function in C or C++.

public void run() throws Exception {

The next two lines perform the actual work of the class. In this case, you want to write the text "Hello World" out to the browser. In order to do this, the first thing that you need is a place to write the text. This may seem obvious, but remember the class doesn't know what you want to do. Fortunately, Netscape has included a method called getOutputStream(), which provides us a means to get to the stream of data going back to the client.

PrintStream out = getOutputStream();

Finally, now that you have access to the stream handler you can place the text "Hello World" on the browser screen. To do this, use the println() method provided in the PrintStream class.

out.println ("HelloWorld");

The last two lines can also be written as:

getOutputStream.out.println("Hello World");

if you prefer. If you are used to the syntax System.out.println(), this may make more sense to you.

Creating and Compiling the HelloWorld Application

To create this application, copy the contents of listing 13.3 into your favorite text editor. Then compile them using the javac program supplied with Sun's JDK.

NOTE
In order to compile a Java application, you need to obtain a copy of the Java Developers Kit (JDK) supplied by Sun Microsystems. Among other things, this kit contains a compiler that can take the source code, such as that in Listing 13.1, and convert it into a Java class file. You can obtain the JDK at http://www.javasoft.com/java.sun.com/products/JDK/index.html.

Including the Netscape Package in the Classpath

The Syntax for compiling the HelloWorld Application is not quite as simple as for most Java code. The reason for this is that we need to import a class from the Netscape package. As a result, it is necessary to include the file that contains the package in the classpath.

Before you can include the file though, it's necessary to determine where the file is located. What you will be looking for is a file called serv2_0.zip. By default this file is located at:

/usr/ns-home/plugins/java/classes/serv2_0.zip

You need to substitute the /usr/ns-home directory with the correct directory for your Enterprise or FastTrack server. As with the rest of this chapter, the location that is used for the installation is /optl/ent-home so the actual path is:

/optl/ent-home/plugins/java/classes/serv2_0.zip

but your installation is likely to be different. To obtain the proper file name, substitute /optl/ent-home for the directory in which you have installed the FastTrack or Enterprise server.

CAUTION
In addition to the serv2_0.zip, you may need to know the location of the classes.zip file included with the JDK. This file is located in the /java/lib directory. For the purposes of this chapter, the file is located at /optl/java/lib/classes.zip.
As with the location of the serv2_0.zip file, you need to substitute the actual directory in which you have installed the JDK.
If you obtain an error, such as
class java.io.PrintStream not found on import
the odds are that you need to also add the classes.zip file to your classpath.

Once you have located the classes.zip and serv2_0.zip files, there are two ways to add them to the class path. The first and simplest way is to do so on the command line. To compile the HelloWorld file, include the netscape package in the class path as shown in the following command line:

javac -classpath /optl/ent-home/plugins/java/classes/serv2_0.zip HelloWorld.java

This should produce a file, called HelloWorld.class, in the directory you have the HelloWorld.java file in.

If you are like most people, you don't really want to have to type out 81 characters every time you want to compile the HelloWorld program. To eliminate the need to always specify the -classpath option, you can set an environment variable called CLASSPATH to point to the serv2_0.zip file. Once the CLASSPATH has been set, you can compile a program in much the same way you would any other Java application.

To set the CLASSPATH variable using CSH, type CLASSPATH=/optl/ent-home/plugins/java/classes/serv2_0.zip export CLASSPATH.

TIP
Windows NT users, note that the examples given here are for UNIX machines. When using an NT machine, the directories should use the backslash (\) instead of the forward slash (/). To set an environment variable, you need to use the set command.

set classpath=\ns-home\plugins\java\classes\serv2_0.zip

Once you have set the CLASSPATH variable, you can compile the HelloWorld application by typing javac HelloWorld.java.

Viewing the HelloWorld Application

To be able to run the HelloWorld application, copy the HelloWorld.class file, which the compiler produced, into the directory you specified when you configured the Enterprise, or FastTrack server to enable the Java Interpreter. If you placed the HelloWorld.java file in this directory, and compiled it there, there is no need to move anything. It will already be in the correct location.

To test out the HelloWorld application, open the URL /server-java/HelloWorld in any browser. It does not need to be a Java-enabled browser such as Netscape Navigator. Figure 13.4 shows the page you should see.

Figure 13.4 : The HelloWorld application should generate a simple page in your browser.

As you can see from figure 13.4, the application that you wrote produced something, which, to your browser, looked exactly as it were coming from a HTML file. Of course, this was a lot of work to produce a simple line of text, but before you learn to surf the big waves, it is generally a good idea to learn to swim first.

A Bigger Greeting Example

Now, let's take a look at a more advanced Java application, which shows some information about the incoming browser. Listing 13.3 shows the source code for the new application.


Listing 13.3  Greetings Java Source Code, a Server Side Applet that Displays Browser Information
import netscape.server.applet.HttpApplet;

import java.io.PrintStream;
import java.net.Socket;
import java.net.InetAddress;

public class Greetings extends HttpApplet {

public void run() throws Exception {
     //Check to find out if browser can accept normal text output
     if (returnNormalResponse("text/plain")) {
        //Get the output stream to send data to client
        PrintStream out = getOutputStream();

        //get the socket the browser is connected to
        Socket client = getClientSocket();

        //find the hostname of the socket
        String clientAddress = client.getInetAddress().getHostName();

        //Check to see if it's my IP address
        if (clientAddress.compareTo ("206.31.43.250")==0)
                out.println("Greetings great and wonderful master!");
        else
                out.println("Nice to meet other netezins");

        //Find out what browser the client is using
        String browser = getHeader ("user-agent");
        if (browser != null){
                if (browser.startsWith ("Mozilla"))
                        out.println ("Your using Netscape... Hey this is a Netscape Server too!");
                else
                        out.println("You're using the" + browser+" browser");
         }
         else
                out.println("Hey, your browser didn't identify itself.");

        }
}

} //end class Greetings

Notice that just like our HelloWorld example, the very first thing that you need to write is:

import netscape.server.applet.HttpApplet;

This includes the class from the Netscape library into the Java environment. Netscape actually provides four classes to assist the construction of server side applications. These four are:

Each of these classes provides a means to access data about the server or the client in order to make writing server applications easier.

Each different class contains various methods to place or get information about the environment. In the HelloWorld example, the only method which we used was getOutputStream(). The Greetings shows the use of several more of methods in HttpApplet.

The first line in the Greetings class shows an example of one such method. Before you blindly write to the browser (like you did with the HelloWorld application), it is better to first check to make sure that the browser is willing to accept text output. If not, you may have to respond differently, so the first line of the Greetings application checks to see if the browser has a standard "text/plain" response.

if (returnNormalResponse("text/plain")) {

After you have verified the browser response, the application opens the output stream, just as it did in the HelloWorld application. Once the connection has been established to the browser, the program proceeds to send data, the same way that it did for HelloWorld.

Now, it's often convenient to know who is accessing your server. Based on who it is, you might want to give a different response to the user, so let us retrieve some information about the client accessing the Greetings app.

The next line of code defines a Socket variable that points to where the client has attached. If you're familiar with Java programming, this socket can be used just as it would in any other Java application.

Once you have a pointer to the client socket, you can use it to determine the address the client browser is coming from, using the getInetAddress() method. Once, you have the client's IP address, you can use it to determine if the client is a valid host, or someone else. In this example, I choose to simply have the application greet my computer differently than other people on the net.

        //get the socket the browser is connected to
        Socket client = getClientSocket();

        //find the hostname of the socket
        String clientAddress = client.getInetAddress().getHostName();

        //Check to see if it's my IP address
        if (clientAddress.compareTo ("206.31.43.250")==0)
                out.println("Greetings great and wonderful master!");
        else
                out.println("Nice to meet other netezins");

NOTE
For experienced Java programmers, it might be interesting to note that the getClientSocket() method is not one from HttpApplet, but rather from its parent ServerApplet.
The getInetAddress() and getHostName() methods are not part of the Netscape package at all, but rather part of members of the java.net package.

Another useful piece of information to use is what type of browsers are accessing your pages? If they are not Netscape-compliant, you may actually want to give them a completely different Web page. The next several lines of the Greetings application deal with doing just that. First, the type of browser is obtained using the getHeader method. This method can be used to retrieve a variety of information about the standard HTTP header. The HTTP header contains a lot of information about the browser, but the one we're interested in is the agent (or browser) that the incoming request is coming from. This information is contained in the user-agent portion of the header. To retreive the various other pieces of information contained in the header, the string user-agent should be substituted with the appropriate title.

//Find out what browser the client is using
String browser = getHeader ("user-agent");

You may initially wonder about the next line of the code, which reads:

if (browser != null){

It's important to make sure that you actually received a string from the getHeader request, because unfortunately, it is not always the case that information obtained using the various methods will actually return data. For instance, some browsers do not return information about who they are. If this is the case, the method will return null, and unless you check for this, you will run into problems using the string.

I decided that if the browser that was coming in was a Netscape Navigator browser (or any browser claiming to be Netscape), I would give the user a friendly hello. To do this, you need to compare the browser name with Mozilla. In fact, all you really care about is, does the browser's name start with Mozilla. And, if not, you will simply give them another message.

Using JavaScript on the Server

In addition to providing the ability to include Java applications on the server, Netscape also extended its JavaScript technology for server side use. This technology was placed into what Netscape calls the LiveWire program. With LiveWire JavaScript, pages, which produce data on the server side, can be written. Because the pages are processed on the server side, these pages can be viewed by any browser, not just the ones from Netscape that support JavaScript.

Enabling LiveWire on the Server

In order to utilize the LiveWire applications, it is first necessary to activate LiveWire on your server. To do this, go to the Server Control center page, and select the programs menu. Now, select the LiveWire sub-menu and activate LiveWire for your server as shown in figure 13.5.

Figure 13.5 : Enable LiveWire on the Enterprise or FastTrack Servers.

Once you have enabled LiveWire for your server, you can then go to the LiveWire Application manager. To access the manager, open the URL /appmgr in your browser. The appmgr is located at the URL of your standard Web page, NOT on the administration port. The Application Manager is shown in figure 13.6.

Figure 13.6 : The LiveWire Application Manager is where you control LiveWire applications.

Now, don't go looking for the appmgr directory in your docs directory. The Application Manager and all other LiveWire applications are symbolically linked into the server.

Running Some LiveScript Applications

Now that you have the Application Manager up and running, it's possible to run some of the sample applications that come with the server. To test a typical LiveWire application, select the application from the Applications list box. For instance, select Hangman and then press the run hyperlink as shown in figure 13.7. You should see the Hangman page come up as shown in figure 13.8.

Figure 13.7 : Select Hangman and click the run hyperlink.

Figure 13.8 : The Hangman applications.

Writing LiveScript Pages

The Hangman application is a bit complicated for this chapter, so let's take a look at a simpler application. The application we will be looking at (used in the previous Java section) is the HelloWorld example.

Listing 13.4 shows the source code for the HelloWorld application, also available in the demo applications List Box.


Listing 13.4  The HelloWorld Application as Written Using JavaScript for LiveWire
<html>
<head>
<title> Hi There </title>

</head>
<body>
<h1> Hi There </h1>
<server>write("<P>The last time you where here you entered " + client.oldtext + ".");</server>
<P>But this time you entered <server>write(request.newtext);</server>

<server>client.oldtext = request.newtext; </server>

<p>Your IP address this time is <server>write(request.ip);</server>
<br>The last person to access this page was <server>write(project.lastAccess);</server>.


<server> 
project.lock();    // Initialize or increment total number of accesses.
    project.lastAccess = request.ip;
project.unlock();


  if (client.count == null)  
    client.count = 0;
  else
    client.count = parseInt(client.count,10) + 1;

</server>

<p>Oh, by the way, you have been here <server>write(client.count);</server> times before.

<h1> Enter some text below </h1>
<form method="post" action="hi2.html">
<input type="text" name="newtext" size="20">
<br>
<p><input type="submit" value="Submit">  
</form>


</body>
</html>

Notice that much of the code looks very similar to standard HTML. This is, in fact, the great benefit of using JavaScript/LiveWire to write programs you might otherwise have written in Perl or some other language. Since JavaScript utilizes the standard HTML format, you can first create a page to look like you would want it to under normal circumstances, and then enhance it using JavaScript.

To understand the JavaScript page, let's once again break it down line by line, as we did for the Java applications.

JavaScript Pages Start with HTML

Each JavaScript program is built around a standard HTML page; so, as with regular HTML pages, these pages must begin with <HTML>, <HEAD> and <BODY> tags.

<html>
<head>
<title> Hi There </title>

</head>
<body>

The most basic page could actually end with the next line, which, just like standard HTML, creates a level one header and writes Hello World.

<h1> Hi There </h1>

Including JavaScript in LiveWire pages

Starting with the next line, the HelloWorld script becomes different. Notice the <SERVER> and </SERVER> tags? These tags tell the server to perform some action with this part of the text.

There are two ways to include JavaScript information in a LiveWire page. The first is to include JavaScript execution instructions between the <SCRIPT> and </SCRIPT> tags. The second way to include JavaScript in a LiveWire page is to include JavaScript variables between back quotes ('). But you can only include variables between back quotes, not instructions.

In the previous line of code, you are introduced to the write() function. This function tells the LiveScript server to write text in this location. The write function is one of the most important ones of LiveWire because it lets you add text to an existing document.

The text that you directed LiveScript to write comes from the request objects IP. That is the IP of the client accessing the page. There are four basic objects in the LiveWire set. These are:

Displaying Text from the Client-Cookie

The next line of code demonstrates the use of the client object. This object is specified by default by the client-cookie. If you reload this page, the client object will be the same for that browser. Notice that you can add and remove variables from the client object at will.

<server>write("<P>The last time you where here you entered " + client.oldtext + ".");</server>

Next, the program displays the value of the newtext variable. This value comes from the form data you will see later, when we cover the form at the bottom of the page.

<P>But this time you entered <server>write(request.newtext);</server>

Saving Data to the Client Object

The next task is to put the newtext value somewhere so that the next time you load in the page, you can tell the user what they had typed this time. The place to store this is the client.oldtext variable we saw just two paragraphs ago. The client object, since it is a client cookie, is stored for each different client separately.

<server>client.oldtext = request.newtext; </server>

Displaying the Client's IP Address

As you did with the Java example, let's print out the IP address from which the client is connecting. To do this, you will need to access the request.ip value, which stores this information.

<p>Your IP address this time is <server>write(request.ip);</server>

I thought it might be interesting to also tell the user who/where the last user came from. To do this, I have stored the IP address of the last access in a variable called project.lastAccess.

<br>The last person to access this page was <server>write(project.lastAccess);</server>.

Storing a Value to the Project Object

Actually, storing the project.last access value is the function of the next three lines. The project object is shared between all instances of the Hi.html page, and since we want each page to be able to tell us who the last person was, the page must use the project object that is shared between all applications.

What happens, though, when multiple pages are accessed at the same time? If two programs tried to read lastAccess in at the same time, and then update it, the odds are that only one of the changes would actually take place. To prevent this kind of activity, LiveWire allows you to lock an object. Once the variable is locked, no other page can access or change the information in that object, until it has been unlocked. So the file continues, by first locking the project object, updating it, and then unlocking it so that other pages can read in the values.

project.lock();    // Initialize or increment total number of accesses.
    project.lastAccess = request.ip;
project.unlock();

In addition to name information, the HelloWorld page also keeps and displays some statistical information about the use of the Web page. The information about the total number of accesses by this client will be stored in the variable client.number.

The first time through the page for a unique client, the Web page initializes the number of accesses to 0. You can determine if the number value has ever been initialized before by finding out if it is null. The Hi There page uses the if...else construct to first determine this (if the value is null) and then increment or initialize the value of client.number depending on the result.

if (client.count == null)  
    client.count = 0;
  else
    client.count = parseInt(client.count,10) + 1;

Finally, the updated values of the client.number are written to the client.

<p>Oh, by the way, you have been here <server>write(client.count);</server> times before.

The Input Form

In the next several lines, the program returns to what you should be familiar with under standard HTML. Notice that the form data is written exactly as it would be for regular HTML.

<h1> Enter some text below </h1>
<form method="post" action="hi2.html">
<input type="text" name="newtext" size="20">
<br>
<p><input type="submit" value="Submit">  
</form>

Compiling JavaScript Pages

The first task in creating the HelloWorld application is to copy the contents of listing 13.4 into a file called Hello.html using a standard editor such as nedit or vi. Once you have a file containing the code, the next step is to compile this page into a LiveWire document or .web file.

There are two ways to compile JavaScript applications. The first is with the command line compiler; the second is using the Application Manager. The second method has been promised by Netscape, but at the time of this writing is unavailable, so we will only cover the command line compiler.

The compiler included with LiveWire is the program lwcomp. The lwcomp program should install in your LiveWire/bin directory, and you may wish to include this in your path.

Now, to compile your HelloWorld example, all you need to do is type:

lwcomp hi.html

If you look in the directory where the hello.html file is located, you should now find two additional files: build and hello.web. Lwcomp has many other options which enable you to link multiple html files in, but they are beyond the scope of this chapter.

Now that you have built your application, you need to add it to the Application Manager so that it can access your new page. To do this, select add from the Applications Manager.

The side window should now switch to the Add function, as shown in figure 13.9. You need to specify the name of the application. This name also appears in the directory that is accessed from your Web browser. In this case, that means that you access it as http://www.yourcompany.com/Hi/. The Web File Path is the actual full name of the Hi.web file that you created using lwcomp. This directory need not reside within your server directory, as demonstrated in this example. Finally, include the default file name that you wish to have the server send. This file is probably the name of the HTML file you used to create the .web file. The file name for the default page is relative to the .web file, so you need not include the entire path.

Figure 13.9 : Add the Application to the Application Manager.

NOTE
You should not use an Application name that is the same as any directory in your Web servers docs directory. The LiveWire application overrides this directory and you won't be able to access the contents of the actual directory in docs.

Testing the LiveScript Page

You can access the HelloWorld Web page to test it in one of two ways. First, after you add the Application to the manager, you can click the run hyper link and it will automatically launch another browser and take you to your new Web page.

Alternatively, you can access the Web page by opening the directory that has the same name as the application.

Java and JavaScript Resources

There are a number of locations on the Web that specialize exclusively in indexes on Java and JavaScript applications.

Example Applets and JavaScript Pages

One of the largest directories currently available is Gamelan:

http://www.gamelan.com

JARS or the Java Applet Review System is another great site which rates applets on a top 1%, 5% and 25% basis:

http://www.jars.com

Apple Flavored Java is a site dedicated to Java on the Macintosh:

http://www.seas.upenn.edu/~mcrae/projects/macjava/

The Java Centre is a UK site:

http://www.java.co.uk/javacentre.html

The Java Boutique is a collection of Java Applets. One of the requirements of this site is that, to be listed, the source for the applet must be made available.

http://weber.u.washington.edu/~jgurney/java

Finding a Java Consultant

Since often you won't have the time to develop a custom applet or JavaScript of your own, the following sites can help you find a developer who can perform that task for you. These sites are also a good location to look for Java applications and applets that have already been written and which are free or very inexpensive.

MagnaStar Inc. A Custom Java programming and consulting company:

http://www.magnastar.com

Dimension X. A developer of Java applications:

http://www.dnx.com

Team Java. A resource that boasts a good list of Java Developers:

http://www.teamjava.com