[View INPRISE Home Page][View Product List][Search This Web Site][View Available Downloads][Join Inprise Membership][Enter Discussion Area][Send Email To Webmaster]
JBuilder Home Page

Building Java Servlets with JBuilder
Written by Live Software, Inc.

Part III

NOTE: The views and information expressed in this document represent those of its author(s) who is solely responsible for its content. Borland does not make or give any representation or warranty with respect such content.

Return to Part I
Return to Part II

Example: Creating a Simple HTTP/RMI/CORBA Test Applet

The purpose of this topic is to help you become acquainted with invoking a servlet from an applet using the HTTP, RMI, or CORBA transport. This example continues from Example: creating a JDBC servlet as RMI server and Example: creating a JDBC servlet as CORBA server. In this example you will learn how to:

  • Invoke a servlet from an applet
  • Invoke a servletÆs method through RMI
  • Invoke a servletÆs method through CORBA
  • Start the Visibroker Smart Agent within JBuilder
  • Start the RMI Registry within JBuilder

See also:
Creating distributed applications with CORBA
Distributed computing with Java RMI

A Simple Test Client
Our test client will basically be an aggregate of objects of type ITransportClient. See Example 4-1. ITransportClient is an interface with a single method called executeQuery(). For illustration purposes weÆve implemented three subclasses of ITransportClient. Namely HTTPTransportClient, CORBATransportClient, and RMITransportClient. See the following code listing.

Example 4-1: ITransportClient.java


package JBExamples.database.applets;

public interface ITransportClient {
  public String executeQuery(String query) throws Exception ;
}
The following example is a class which performs a connection to the database servlet through the HTTP transport. It illustrates how general applet-servlet communication can be carried out using a POST.

Example 4-2: HTTPTransportClient.java


package JBExamples.database.applets;

import java.util.*;
import java.net.*;
import java.io.*;

public class HTTPTransportClient implements ITransportClient {
  String servletLoc;

  public HTTPTransportClient(String servletLoc) {
    this.servletLoc = servletLoc;
  }

  /**
   * This method illustrates how to communicate to the JDBCServlet using
   * the HTTP transport.
   * This method also illustrates how general applet to servlet communication
   * can be carried out.
   */
  public String executeQuery(String queryString) throws Exception {
    StringBuffer results = new StringBuffer();

    //The value of dbquery has to be urlencoded to be passed through http.
    String postData   = "dbQuery="+URLEncoder.encode(queryString);

    URL action = new URL(servletLoc);
    URLConnection url = action.openConnection();

    url.setDoInput(true);
    url.setDoOutput(true);
    url.setUseCaches(false);
    url.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    url.setRequestProperty("Content-length", "" + postData.length());

    // Write out post data
    DataOutputStream out = new DataOutputStream(url.getOutputStream());
    out.writeBytes(postData);
    out.flush();
    out.close();

    // Get response
    DataInputStream in = new DataInputStream(new BufferedInputStream(url.getInputStream()));

    String line;
    while(null != ((line = in.readLine())))
      results.append(line + "\n");

    return results.toString();
  }

}
The above example is relatively straight forward. In the executeQuery() method, the given query string is url encoded using the method URLEncoder.encode(queryString). A url connectioon is made to the servlet using the URL and URLConnection objects. Appropriate headers and data is sent in bytes, and the results are read back in from the servlet and returned. Since this particular query talks to the servlet through itÆs service method, if you recall, the results will be in an HTML formatted table.

The following example illustrates how to invoke methods of the database servlet remotely using RMI.

Example 4-3: RMITransportClient.java


package JBExamples.database.applets;

//Packages for RMI support
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.*;

//RMI objects
import JBExamples.database.servlets.rmi.IDBQuerier;
import JBExamples.database.servlets.rmi.IDataTable;

public class RMITransportClient implements ITransportClient {
  String serverName;
  IDBQuerier dbQuerier = null;

  public RMITransportClient(String serverName) throws Exception {
    this.serverName = serverName;

   //Install a security manager.  Doing this will allow this client to load
   //stubs remotely.
    if (System.getSecurityManager() == null)
      System.setSecurityManager(new RMISecurityManager());

    //Get a remote reference to the JDBCRmiServlet object
    dbQuerier = (JBExamples.database.servlets.rmi.IDBQuerier)Naming.lookup(serverName);
  }

  /**
   * This method illustrates how to communicate to the JDBCRmiServlet using
   * the RMI transport.
   */
  public String executeQuery(String queryString) throws Exception
  {
    if( dbQuerier == null ) return "DBQuerier is null";

    StringBuffer results = new StringBuffer();
    //Try to fetch an IDataTable object from the IDBQuerier. IDataTable
    //should contain the results of the query.
    IDataTable dataTable = dbQuerier.getResultTable(queryString);

    if( dataTable == null ) return "Data is null";

    return dataTable.toTableString();

  }

} 
The following example illustrates how to invoke methods of the database servlet remotely using CORBA. The class CORBATransport client is another class implementing the ITransportClient interface.

Example 4-4: CORBATransportClient.java


package JBExamples.database.applets;

//Packages for CORBA support
import org.omg.CORBA.*;
import JBExamples.database.servlets.corba.IDBQuerierHelper;

//CORBA objects
import JBExamples.database.servlets.corba.IDataTable;
import JBExamples.database.servlets.corba.IDBQuerier;

public class CORBATransportClient implements ITransportClient
{
  //Server's identifier
  String serverName;
  IDBQuerier dbQuerier = null;

  public CORBATransportClient(String serverName) throws Exception {
    this.serverName = serverName;

    //Inititialize the orb
    String[] args = new String[0];
    ORB orb = ORB.init(args, null);

    //Get a remote reference to the JDBCCorbaServlet object
    dbQuerier = IDBQuerierHelper.bind(orb, serverName);
  }

  public String executeQuery(String queryString) throws Exception {
    StringBuffer results = new StringBuffer();

    if( dbQuerier == null ) return "DBQuerier is null";

    //Try to fetch an IDataTable object from the IDBQuerier. IDataTable
    //should contain the results of the query.
    IDataTable dataTable = dbQuerier.getResultTable(queryString);

    if( dataTable == null ) return "Data is null";

    return dataTable.toTableString();
  }
  
}
The following code listing is the completed test client weÆve defined as JDBCApplet, and its corresponding HTML file.

Example 4-5: JDBCApplet.java


package JBExamples.database.applets;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.io.*;
import java.util.Hashtable;


/*
 * A class that shows how to access an RMI or CORBA servlet from an    
 * applet.
 * Since both objects are also servlets they both can be accessed via the
 * HTTP transport.
 */
public class JDBCApplet extends Applet implements Runnable {
  Thread t = null;
  TextArea textArea;
  TextField textField;
  Button queryButton;
  Choice jdbcClients;

  Hashtable transportClients = new Hashtable();

  String HTTP  = "HTTP";
  String RMI   = "RMI";
  String CORBA = "CORBA";

  //A variable that specifies the name of the servlet to be accessed using
  //the HTTP transport.  The servlet is accessed using the servlet's alias.
  //Servlet aliasing can be set through the servlet runners admin tool.
  //The alias to the JDBCRmiServlet is assumed to be set to RMIServlet
  //The alias to the JDBCCorbaServlet is assumed to be set to CORBAServlet
  //String servletName = "CORBAServlet"; //Use the corba servlet as the plain servlet
  String servletName  = "RMIServlet"; //Use the rmi servlet as the plain servlet

  //Construct the applet
  public JDBCApplet() {
  }
  
  //Initialize the applet
  public void init() {
    super.init();
    try {
      jbInit();

      //Initialize transport clients
      transportClients.put( HTTP,  new HTTPTransportClient(getCodeRoot()+"/servlet/"+servletName));
      transportClients.put( RMI,   new CORBATransportClient("DBQuerier") );
      transportClients.put( CORBA, new RMITransportClient("DBQuerier") );

    } catch (Exception e) { e.printStackTrace(); }
  }

  //Component initialization
  private void jbInit() throws Exception {
    setSize(new Dimension(300, 300));
    setLayout(new BorderLayout());

    //Build the mainPanel
    Panel mainPanel = new Panel();
    mainPanel.setLayout(new BorderLayout());

    //Build north part of mainPanel
    Panel northPanel = new Panel();
    northPanel.setLayout(new GridLayout(2,2) );
    northPanel.add(new Label("Query String: "));

    textField = new TextField();
    textField.setColumns(25);
    northPanel.add(textField);

    jdbcClients = new Choice();
    jdbcClients.add(HTTP);
    jdbcClients.add(RMI);
    jdbcClients.add(CORBA);

    northPanel.add(new Label("JDBC Client Call Through:"));
    northPanel.add(jdbcClients);

    mainPanel.add("North", northPanel);

    //Build a blank textArea and center in the panel
    textArea = new TextArea();
    textArea.setEditable(false);
    mainPanel.add("Center", textArea);

    //Build the button panel
    Panel buttonPanel = new Panel();
    this.queryButton = new Button("Query");
    this.queryButton.addActionListener(
      new ActionListener()
      {
        public void actionPerformed(ActionEvent event)
        {
          try {
            String selectedClient = jdbcClients.getSelectedItem();

            //Get the correct transport client
            ITransportClient client = (ITransportClient)transportClients.get(selectedClient);
            doQuery(client);
          }
          catch(Throwable e) {
            e.printStackTrace();
            textArea.setText("An exception occured trying to locate the server.\n"+
              "Here it is: "+e.toString());
            textArea.show();
          }
        }
      }
    );

    buttonPanel.add("Center", queryButton);
    mainPanel.add("South", buttonPanel);

    add("Center", mainPanel);
  }

  public void run() {
    if( t == null ) {
      this.t = new Thread(this);
      t.start();
    }
  }

  public void stop() {
    if( t != null ) {
      t.stop();
      t = null;
    }
  }

  public Insets insets() {
    return new Insets(10,10,10,10);
  }

  /**
   * Execute the query using the given ITransportClient
   */
  public void doQuery(ITransportClient client) {
    String queryString = textField.getText();

    try {
      String results = client.executeQuery(queryString);
      textArea.setText( results );
    }
    catch(Exception e) {
      e.printStackTrace();
      textArea.setText("An exception occured trying to execute the query.\n"+
        "Here it is: "+e.toString() );
    }
    
    textArea.show();
  }

  /**
   * Get Applet information
   */
  public String getAppletInfo() {
    return "Applet Information";
  }

  /**
   * Get parameter info
   */
  public String[][] getParameterInfo() {
    return null;
  }

  /**
   * Find the code root.
   */
  private String getCodeRoot() {
    String codeRoot;
    String codeBase = getCodeBase().toString();
    int i=0, count=0;
    while(count < 3) {
      if(codeBase.charAt(i++) == '/')
        count++;
      if(i > codeBase.length())
        break;
    }

    if(i < codeBase.length())
      codeRoot = codeBase.substring(0, i);
    else
      codeRoot = codeBase;
            
    while(codeRoot.endsWith("/"))
      codeRoot = codeRoot.substring(0, codeRoot.length()-1);
            
    if(codeRoot.startsWith("http://") == false && codeRoot.startsWith("file://") == false )
      codeRoot = "http://" + codeRoot;

    return codeRoot;
  }


}

Example 4-6: JDBCApplet.html

<TITLE>
JDBC Applet Page
</TITLE>
</HEAD>
<BODY>
JDBCApplet will appear below in a Java enabled browser work<BR>
<APPLET
  CODEBASE = "."
  CODE     = "JBExamples.database.applets.JDBCApplet.class"
  NAME     = "JDBCApplet"
  WIDTH    = 400
  HEIGHT   = 300
  HSPACE   = 0
  VSPACE   = 0
  ALIGN    = middle
>
</APPLET>
</BODY>
</HTML>

Starting the Visibroker Smart Agent, an the RMI registry within JBuilder
  • To start up VisibrokerÆs Smart Agent, in the main menu, click on Tools|Visibroker Smart Agent
  • To start up the RMI registry, in the main menu, click on Tools|RMI Registry.

Putting it all together

Once the RMI registry, and Visibroker have started up, the next step is to start up the Web Server. Before starting up the web server make sure your servlets are set to load on init, if you have not done so, see the section Loading On Init. Using appletviewer throught the DOS prompt, make sure your system classpath is set to use JBuilderÆs database classes.

Conclusion

The rising popularity of Java Servlet technology is at an unrivaled pace that signifies the hungering success of the internet. This relatively new technology is indeed a quieting factor for those demanding efficient internet solutions. For more information on servlets, visit the Live Software web site at http://www.livesoftware.com.

Appendix A

Servlet Resources

Back To Top
Return to Part I
Return to Part II
Home Page

© 1998 by Live Software, Inc., San Diego, California 92121. All rights reserved. No part of this document may be reproduced, stored in a retrieval system, or transcribed, in any form or by any means û electronic, mechanical, photocopying, recording, or otherwise û without the prior written permission of the publisher, Live Software, Inc., 5703 Oberline Dr. Suite 208, San Diego, California, 92121.

Trademarks & Copyright © 1998 INPRISE Corporation.