"CORBA vs. Servlets," Volume: 4 Issue: 3, p. 16

Listing 1.
* Client.java
 */

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/**
 * This class demonstrates a simple client side
 * applet that uses CORBA for communication with 
 * the server.  It takes in two text fields,
 * name and hourse, and deposits them in an
 * Oracle database using Inprise VisiBroker.
 */
public class Client extends Applet 
  implements ActionListener {
 

  // Server is the handle to the server side
  // code, accessed by the ORB.
  private Server server;
 

  // The name to pass to the database
  private TextField name;
 

  // The hours string to pass to the database
  private TextField hours;
 

  /**
   * The init method of the applet contains the
   * initialization of the ORB.
   */
  public void init() {
    // This line is where the ORB is
    // initialized.
    org.omg.CORBA.ORB orb = 
      org.omg.CORBA.ORB.init(this, null);
 

    // Next, the server object is bound to
    // the actual object on the server side.
    server = ServerHelper.bind(orb, "Server");
 

    // This method just sets up the GUI.
    gridBagLayout();
  }
 

  /**
   * gridBagLayout creates a simple GUI
   * to communicate with the server code.
   */
  public void gridBagLayout() {
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    GridBagConstraints c = 
      new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.0;
    c.weighty = 0.0;
    Label label = new Label("Name:");
    gbl.setConstraints(label, c);
    add(label);
    c.gridy = 1;
    label = new Label("Hours worked:");
    gbl.setConstraints(label, c);
    add(label);
    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    name = new TextField(15);
    gbl.setConstraints(name, c);
    add(name);
    c.gridy = 1;
    hours = new TextField(15);
    gbl.setConstraints(hours, c);
    add(hours);
    c.gridy = 2;
    Button button = new Button("Submit");
    button.addActionListener(this);
    gbl.setConstraints(button, c);
    add(button);
  }
 

  /**
   * When the Submit button is pressed, this
   * method is called.  This is where the
   * actual communication with the server
   * takes place.
   */
  public void actionPerformed(ActionEvent evt) {
    // The Data object defined by the IDL file
    // is initialized just like any other object
    // in Java.
    Data data = new Data();
 

    // The data is filled in from the text
    // fields.  In a commercial application,
    // error checking and validation would
    // happen here.
    data.name = name.getText();
    data.hours = hours.getText();
 

    // The method in the server code that
    // records data is called as if it were
    // on the client side, and returns a
    // value the same way.
    if (server.record(data) == false) {
      destroy();
    }
  }
 

  /**
   * stop is called before destroy, so
   * the server.close() method must be
   * called here.
   */
  public void stop() {
    // This server side method is called
    // to wrap things up neatly.
    server.close();
  }
 

}
 

-----------------------------------------------
 

// example.idl
 

// This is the IDL file that defines the objects
// and interfaces accessible to the client and 
// server.
 

// The Data struct, when converted to Java, will
// create a Java Data object and a few helper
// files that facilitate communication.
struct Data {   
  string name; 
  string hours;
};
 

// Server is an interface, implemented by
// ServerImpl.java on the server side.  All
// server methods accessed by the client must
// be listed here.
interface Server { 
  boolean record(in Data data);
  boolean close();
};
 

------------------------------------------------
 

/*
 * ServerImpl.java
 */
 

import java.sql.*;
 

/**
 * Server.java implements the methods defined in t
 * the IDL file.  It uses JDBC to connect to an
 * Oracle database.  It extends the IDL defined
 * ServerImpl class, which implements the Server
 * interface defined in the IDL.  The Java files
 * referred to are created by the utility that
 * maps IDL files to Java classes.
 */
public class ServerImpl extends _ServerImplBase {
 

  // This is the database connection object.
  Connection connection;
 

  /**
   * The constructor does the initialization
   * required by the parent class, and sets up
   * the database connnection.
   */
  public ServerImpl(String name) {
    super(name);
    try {
      // The following two lines connect to the
      // database and initialize the connection
      // object.
      Class.forName
        ("oracle.jdbc.driver.OracleDriver");
      connection = DriverManager.getConnection
        ("jdbc:oracle:thin:imparto/password" +
         "@databasem:1521:ORCL2");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 

  /**
   * record() is the method that takes in the
   * client data (passed using the IDL defined
   * Data object) and inserts it into the
   * database.
   */
  public boolean record(Data data) {
    PreparedStatement statement = null;
    String sqlstring;
    try {
      // The prepared statement inserts the
      // data into the SQL update, which 
      // is passed to the database.
      sqlstring =
        "INSERT into user_data " +
        "(name, hours)" +
        "VALUES (?, ?)";
      statement = connection
        .prepareStatement(sqlstring);
 

      // The following two lines put the
      // actual client data into the
      // statement.
      statement.setString(1, data.name);
      statement.setString(2, data.hours);
      if (statement.executeUpdate() < 0)
        return false;
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      try {
        statement.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
 

  /**
   * This is a utility method to make
   * sure the connection is closed when
   * the client side exits.
   */
  public boolean close() {
    try {
      connection.close();
      return true;
    } catch (Exception e) {
      return false;
    }
  }
}
 

-----------------------------------------------
 

/*
 * ServerWrapper.java
 */
 

/**
 * ServerWrapper initializes the ORB and creates
 * the server side object.
 */
public class ServerWrapper {
  /**
   * The application just initializes everything,
   * loads the ServerImpl object, and notifies
   * the ORB that everything's ready.
   */
  public static void main(String[] args) {
    // This initializes the ORB on the
    // server side.
    org.omg.CORBA.ORB orb = 
      org.omg.CORBA.ORB.init(args, null);
 

    // This initializes the BOA, or Basic
    // Object Adapter.  The BOA is implementation
    // specific, and adapts objects so that they
    // can be understood by the ORB.  It also
    // handles the interface between the server
    // and the ORB.
    org.omg.CORBA.BOA boa = orb.BOA_init();
 

    // The server implementation is
    // instantiated here.
    Server server = new ServerImpl("Server");
 

    // The next two lines tell the BOA to
    // notify the ORB that everything is ready.
    boa.obj_is_ready(server);
    boa.impl_is_ready();
  }
}

Listing 2.
/*
 * ReportApplet.java
 */
 

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
 

/**
 * This is a simple applet that uses a servlet to
 * generate a report.  The applet accepts a name
 * as a parameter - if no name is specified, the
 * whole list is shown.
 */
public class ReportApplet extends Applet 
  implements ActionListener {
 

  // The user name is entered here.
  TextField name;
 

  /**
   * The init method simply calls the layout
   * method.
   */
  public void init() {
    gridBagLayout();
  }
 

  /**
   * gridBagLayout creates a simple GUI
   * to communicate with the servlet code.
   */
  public void gridBagLayout() {
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    GridBagConstraints c =
      new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.0;
    c.weighty = 0.0;
    Label label = new Label("Name:");
    gbl.setConstraints(label, c);
    add(label);
    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    name = new TextField(15);
    gbl.setConstraints(name, c);
    add(name);
    c.gridy = 1;
    Button button = new Button("View Report");
    button.addActionListener(this);
    gbl.setConstraints(button, c);
    add(button);
  }
 

  /**
   * When the Submit button is pressed, this
   * method is called.  This is where the
   * actual communication with the server
   * takes place.
   */
  public void actionPerformed(ActionEvent evt) {
    try {
      // The url string is dependent on where
      // the web server (or servlet runner) is
      // running.
      String urlString = 
        "http://mymachine:8080/" +
        "servlet/ReportServlet";
 

      // If the name isn't filled in, generate
      // the full report (see servlet code).
      // If it is, send the name as part of
      // the query.
      if (!name.getText().equals(""))
        urlString = urlString + "?name=" + 
          name.getText();
      URL url = new URL(urlString);
 

      // Finally, show the report.
      getAppletContext().showDocument(url, "reportWindow");
 

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

----------------------------------------------------------
 

/*
 * ReportServlet.java
 */
 

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
 

/**
 * The report servlet gets the name of a user from
 * the client side, and generates a report from
 * the database.  If no name is specified, the
 * servlet shows the full report.  This example
 * uses an Oracle database.
 */
public class ReportServlet extends HttpServlet {
  
  /**
   * doGet is the primary method for a GET
   * request.  The information about the request
   * is recorded here in req, and information
   * about the response can be set using res.
   */
  public void doGet (HttpServletRequest req, 
                     HttpServletResponse res) {
 

    // The database connection
    Connection connection = null;
 

    // A prepared statement for accessing the
    // database
    PreparedStatement statement = null;
 

    // A result set to hold the database results
    ResultSet resultSet = null;
 

    // The SQL string
    String sqlstring = null;
 

    try {
      
      // The following line gets the value of
      // the parameter "name" from the query
      // string.  lName will be set to null
      // if the parameter is not set.
      String lName = req.getParameter("name");
 

      // The following two lines connect to the
      // database and initialize the connection
      // object.
      Class.forName
        ("oracle.jdbc.driver.OracleDriver");
      connection = DriverManager.getConnection
        ("jdbc:oracle:thin:imparto/password" +
         "@databasem:1521:ORCL2");
      
      // This sets the type to text/html, and
      // opens the output stream.  Anything
      // written to this stream will show up
      // on the generated page.
      res.setContentType("text/html");
      ServletOutputStream out = 
        res.getOutputStream();
      
      // The SQL query depends on whether a
      // name is specified or not.
      if (lName == null) {
        sqlstring = 
          "SELECT name, hours " +
          "FROM user_data";
        statement = 
          connection.prepareStatement(sqlstring);
      } else {
        sqlstring =
          "SELECT name, hours " +
          "FROM user_data " +
          "WHERE name = ?";
        statement = 
          connection.prepareStatement(sqlstring);
        statement.setString(1, lName);
      }
 

      // The result set is pulled from the 
      // database.
      resultSet = statement.executeQuery();
      
      // Before the servlet examines the result
      // set, it sets up the HTML page it is
      // writing to.
      out.println("<html>");
      out.println("<head><title>Name And Hours"
                  + " Report</title></head>");
      out.println("<body>");
      out.println("<h1>Report:</h1>");
      out.println("<table border=1><tr><th>" +
                  "Name</th><th>Hours" +
                  "</th></tr>");
      
      // Now the servlet examines the result
      // set, and adds the information to
      // the report.
      while (resultSet.next())
        out.println
          ("<tr><td>" + 
           resultSet.getString("name") + 
           "</td><td>" + 
           resultSet.getString("hours") + 
           "</td></tr>");
 

      // The HTML page is closed.
      out.println("</table>");
      out.println("</body></html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
 

Download files assoicated with this article