Saturday, July 2, 2011

code fragment gives a simple example of these three steps


public void connectToAndQueryDatabase(String username, String password) {

Connection con = DriverManager.getConnection
("jdbc:myDriver:myDatabase", username, password);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
// ...

code fragment gives a simple example of these three steps

Three programming activities JDBC



JDBC helps you to write java applications that manage these three programming activities:





  1. Connect to a data source, like a database


  2. Send queries and update statements to the database


  3. Retrieve and process the results received from the database in answer to your query

Friday, July 1, 2011

Which one to favor, composition or inheritance?

The guide is that inheritance should be only used when
subclass ‘is a’ superclass.
􀂃 Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code
reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if
the superclass is modified.
􀂃 Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is
polymorphism then use interface inheritance with composition, which gives you code reuse.

How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between compositio

The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
Inheritance [ is a ] Vs Composition [ has a ] Building Bathroom House
class Building{
.......
}
class House extends Building{
.........
}
is a [House is a Building]
class House {
Bathroom room = new Bathroom() ;
....
public void getTotMirrors(){
room.getNoMirrors();
....
}
}
is a has a [House has a Bathroom] has a Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.

How does the Object Oriented approach improve software development?

The key benefits are:
􀂃 Re-use of previous work: using implementation inheritance and object composition.
􀂃 Real mapping to the problem domain: Objects map to real world and represent vehicles, customers,
products etc: with encapsulation.
􀂃 Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.
The increased quality and reduced development time are the by-products of the key benefits discussed above.
If 90% of the new application consists of proven existing components then only the remaining 10% of the code
have to be tested from scratch.

What are the advantages of Object Oriented Programming Languages (OOPL)?

The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account,
Customer etc. The features of the OO programming languages like polymorphism, inheritance and
encapsulation make it powerful. [Tip: remember pie which, stands for Polymorphism, Inheritance and
Encapsulation are the 3 pillars of OOPL

How to call the superclass constructor?

If a class called “SpecialPet” extends your “Pet” class then you can
use the keyword “super” to invoke the superclass’s constructor. E.g.
public SpecialPet(int id) {
super(id); //must be the very first statement in the constructor.
}
To call a regular method in the super class use: “super.myMethod( );”. This can be called at any line. Some frameworks based on JUnit add their own initialization code, and not only do they need to remember to invoke their parent's setup() method, you, as a user, need to remember to invoke theirs after you wrote your initialization
code:
public class DBUnitTestCase extends TestCase {
public void setUp() {
super.setUp();
// do my own initialization
}
}
public void cleanUp() throws Throwable
{
try {
… // Do stuff here to clean up your object(s).
}
catch (Throwable t) {}
finally{
super.cleanUp(); //clean up your parent class. Unlike constructors
// super.regularMethod() can be called at any line.

Can you call one constructor from another?

Yes, by using this() syntax.
E.g. public Pet(int id) {
this.id = id; // “this” means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // ”this” means this object
}

What happens if you do not provide a constructor?

Java does not actually require an explicit constructor in
the class description. If you do not include a constructor, the Java compiler will create a default constructor in the
byte code with an empty argument. This default constructor is equivalent to the explicit “Pet(){}”. If a class includes
one or more explicit constructors like “public Pet(int id)” or “Pet(){}” etc, the java compiler does not create the
default constructor “Pet(){}”.

What is the difference between constructors and other regular methods? What happens if you do not provide a constructor? Can you call one constructor


What are “static initializers” or “static blocks with no function names”?

When a class is loaded, all blocks that are declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields.
public class StaticInitializer {
public static final int A = 5;
public static final int B; //note that it is not 􀃆 public static final int B = null;
//note that since B is final, it can be initialized only once.
//Static initializer block, which is executed only once when the class is loaded.
static {
if(A == 5)
B = 10;
else
B = 5;
}
public StaticInitializer(){} //constructor is called only after static initializer block
}
The following code gives an Output of A=5, B=10.
public class Test {
System.out.println("A =" + StaticInitializer.A + ", B =" + StaticInitializer.B);
}

Explain static vs. dynamic class loading?




What do you need to do to run a class with a main() method in a package?

Example: Say, you have a class named “Pet” in a project folder “c:\myProject” and package named
com.xyz.client, will you be able to compile and run it as it is?
package com.xyz.client;
public class Pet {
public static void main(String[] args) {
System.out.println("I am found in the classpath");
}
}
To run 􀃆 c:\myProject> java com.xyz.client.Pet
The answer is no and you will get the following exception: “Exception in thread "main" java.lang.-
NoClassDefFoundError: com/xyz/client/Pet”. You need to set the classpath. How can you do that? One of the
following ways:
1. Set the operating system CLASSPATH environment variable to have the project folder “c:\myProject”. [Shown
in the above diagram as the System –classpath class loader]
2. Set the operating system CLASSPATH environment variable to have a jar file “c:/myProject/client.jar”, which
has the Pet.class file in it. [Shown in the above diagram as the System –classpath class loader].
3. Run it with –cp or –classpath option as shown below:
c:\>java –cp c:/myProject com.xyz.client.Pet
OR
c:\>java -classpath c:/myProject/client.jar com.xyz.client.Pet

Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?


Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader.
Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

What are the usages of Java packages?

It helps resolve naming conflicts when different packages have classes with the same names. This also helps you
organize files within your project. For example: java.io package do something related to I/O and java.net
package do something to do with network and so on. If we tend to put all .java files into a single package, as the
project gets bigger, then it would become a nightmare to manage all your files.
You can create a package as follows with package keyword, which is the first keyword in any Java program
followed by import statements. The java.lang package is imported implicitly by default and all the other packages
must be explicitly imported.
package com.xyz.client ;
import java.io.File;
import java.net.URL;

What is the difference between C++ and Java?

Both C++ and Java use similar syntax and are Object Oriented, but:
􀂃 Java does not support pointers. Pointers are inherently tricky to use and troublesome.
􀂃 Java does not support multiple inheritances because it causes more problems than it solves. Instead Java
supports multiple interface inheritance, which allows an object to inherit many method signatures from
different interfaces with the condition that the inheriting object must implement those inherited methods. The
multiple interface inheritance also allows an object to behave polymorphically on those methods.
􀂃 Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage
collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means
you do not know when the objects are going to be finalized. Avoid using finalize() method to release nonmemory
resources like file handles, sockets, database connections etc because Java has only a finite
number of these resources and you do not know when the garbage collection is going to kick in to release
these resources through the finalize() method.
􀂃 Java does not include structures or unions because the traditional data structures are implemented as an
object oriented framework.
􀂃 All the code in Java program is encapsulated within classes therefore Java does not have global variables or
functions.
􀂃 C++ requires explicit memory management, while Java includes automatic garbage collection

What is the main difference between the Java platform and the other software platforms?


Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.
The Java platform has 2 components:
􀂃 Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte
codes are the machine language of the JVM.
􀂃 Java Application Programming Interface (Java API) – set of classes written using the Java language and run
on the JVM.

Give a few reasons for using Java?

Java is a fun language. Let’s look at some of the reasons:
􀂃 Built-in support for multi-threading, socket communication, and memory management (automatic garbage
collection).
􀂃 Object Oriented (OO).
􀂃 Better portability than other languages across operating systems.
􀂃 Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI, EJB etc)
and network protocols (HTTP, JRMP etc) with the help of extensive standardized APIs (Application
Programming Interfaces).

An included servlet


package com.ack.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AnIncludedServlet extends HttpServlet {

public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException {
PrintWriter pw = res.getWriter();

/**
* note that a servlet that has been included within another
* servlet has access to both the original request uri, servlet
* path, path info, context path and query string through the
* HttpServletRequest object.
*
* However it also has access to these values that can be different
* depending on how the servlet include was dispatched. The servlet
* engine gives you access to these though request attributes as
* demonstrated before.
*/

pw.println( "

The Included Servlet

" );
pw.println( "
request uri: " +
req.getAttribute( "javax.servlet.include.request_uri" ) );
pw.println( "
context path: " +
req.getAttribute( "javax.servlet.include.context_path" ) );
pw.println( "
servlet path: " +
req.getAttribute( "javax.servlet.include.servlet_path" ) );
pw.println( "
path info: " +
req.getAttribute( "javax.servlet.include.path_info" ) );
pw.println( "
query string: " +
req.getAttribute( "javax.servlet.include.query_string" ) );
}
}

Tuesday, June 28, 2011

Creating vector class

public class Vec2D I
public float dx, dy;
public void setVec (float dx, float dy) I
this.dx = dx;
this.dy = dy;
public float mag () {
return (float) Math.sgrt(dx * dx + dy * dy);
public void addVec (Vec2D vec) I
dx += vec.dx;
dy += vec.dy;
public void subVec (Vec2D vec) I
dx -= vec.dx:
dy -= vec.dy;
public void unitVec () f
float mag = mag();
setVec(dx / mag, dy / mag);
public void mulVec (float scale) t
setVec(dx * scale, dy * scale);

paddle

class Paddle I
public int x, y, width, height;
private Color color;
Paddle (int x, int y, int width, int height,
Color color) I
th'is.x = x:
this.y = y;
this.width = width;
this.height = height;
this.color = color;
public void move (int x, Rectangle bd) I
i f ( x > (width >> 1) && x < (bd.width - (width )> l)))
this.x = x;
public int checkReturn (Ball ball, boolean plyr,
i nt rl, int r2, int r3) I
if (plyr && ball.y > (y - ball.radius)
! plyr && ball.y < (y + ball.radius))
if ((int) Math.abs(ball.x - x) < (width 1 2 +
ball.radius)) I
ball.dy = -ball.dy;
1! Put a little english on the ball
ball.dx += (int) (ball.dx * Math.abs(ball.x - x) /
(width / 2));
return r2;
else
return r3;
return rl;
public void draw (Graphics g) f
g.setColor(color);
g.fillRect(x - (width >> 1), y, width, height);

Monday, June 27, 2011

ball bounce

public void move (Rectangle bounds) I
// Add velocity values dx/dy to position to
get ,
// ball s new position
x +_ dx;
y +° dy;
// Check for collision with left edge
if (x < bounds.x && dx < 0)
dx = -dx;
x -= 2 * (x - bounds.x);
// Check for collision with right edge
else if ((x + size) ) (bounds.x + bounds.width) &&
d x > 0' )
dx = -dx;
x -= 2 * ((x + size) - (bounds.x + bounds.width));
// Check for collision with top edge
if (y < bounds.y && dy < 0) I
dy = -dy;
y -° 2 * (y - bounds.y);
// Check for collision with bottom edge
else i f (( y + size) > ( bounds.y + bounds.height) &&
dy = -dy;
y -= 2 * ((y + size) - (bounds.y + bounds.height));































moving the ball

Wednesday, May 4, 2011

Connecting to the Database


Listing 1: Connecting to the Database

Connection newCon = null;
try{
  Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
  newCon  = DriverManager.getConnection( "jdbc:odbc:nformant200", "username", "password" );
}catch(Exception E){
  System.out.println( "[jdbcServlet.service():" + E + "]" );
  _res.setStatus( HttpServletResponse.SC_NO_CONTENT );
  return;
}

Listing 2: Running the Query

Statement Statmt;
ResultSet Res;
PrintWriter Out = new PrintWriter( _res.getOutputStream() );

try{
  Statmt = newCon.createStatement();
  Res    = Statmt.executeQuery( "SELECT * FROM USER_TABLE" );

  ResultSetMetaData RM = Res.getMetaData();
  while (Res.next()){
    String columnString = "";
    for ( int x=0; x < RM.getColumnCount(); x++ ){
      columnString += Res.getString(x+1) + " ";
    }
       
    Out.println( columnString );
  }

  Res.close();
  Statmt.close();
  newCon.close();
}catch(SQLException E){
  System.out.println( "[jdbcServlet.service():" + E + "]" );
  _res.setStatus( HttpServletResponse.SC_NO_CONTENT );
  return;
}

Listing 3: Setting Up the Connection Pool

public class dbBroker. {

  private static dbBroker Broker = null;

  public synchronized static void getInstance(){
    if ( Broker == null )
      Broker = new dbBroker();
  }
}


Listing 4: Setting Up the Wrapper Class for a Connection

class dbConnection extends Object {
  public Connection Con;
  public boolean    bActive;
  public long       timeTaken;
  public long       averageTime;
  public long       maxTime;
  public int        hitRate;

  public dbConnection( Connection _Con ){
    Con     = _Con;
    bActive = false;
    timeTaken   = 0;
    averageTime = 0;
    hitRate     = -1;
    maxTime     = -1;
  }

  public void setInActive(){
    bActive = false;
    long t = System.currentTimeMillis() - timeTaken;
    if ( t < 120000 )
      averageTime += t;

    timeTaken   = 0;
    if ( t > maxTime )
      maxTime = t;
  }

  public void setActive(){
    bActive = true;
    timeTaken   = System.currentTimeMillis();
    hitRate++;
  }

  public long getAverage(){
    if ( hitRate == 0 ) return 0;

 return averageTime/(long)hitRate;
  }

  public String toString(){
    return "[Hit: " + hitRate + "] [Avg.: " + getAverage() + "]
            [Use: " + bActive + "] [Max: " + maxTime + "]";
  }
}

Listing 5: Creating the Instance of dbBroker

private dbBroker(){
  Properties INI = new Properties();
  try{
    INI.load( new FileInputStream("dbbroker.ini") );
    dbDriver  = INI.getProperty( "driver" );
    dbName    = INI.getProperty( "database" );
    dbUser    = INI.getProperty( "username" );
    dbPassword= INI.getProperty( "password" );
    noCon     = Integer.parseInt(INI.getProperty("connections"));
  } catch (Exception E){
    System.out.println( "[dbBroker:" + E + "]" );
    System.out.println( "[dbBroker: Please ensure you have the following fields: " );
    System.out.println( "[dbBroker: driver=" );
    System.out.println( "[dbBroker: database=" );
    System.out.println( "[dbBroker: username=" );
    System.out.println( "[dbBroker: password=" );
    System.out.println( "[dbBroker: connections=" );
    System.out.println( "[dbBroker: in a file named dbbroker.ini]" );
  }

  dbList  = new Vector();

  //-- Attempt to open the database connections
  Connection Con;
  for ( int x=0; x < noCon; x++ ){
    Con = openConnection();
    if ( Con != null )
      dbList.addElement( new dbConnection(Con) );
  }
}

Listing 6: Opening the Connection to the Database

private Connection openConnection(){
  Connection newCon = null;
  try{
    Class.forName( dbDriver );
    newCon  = DriverManager.getConnection( dbName, dbUser, dbPassword );
  }catch(Exception E){
    System.out.println( "[dbBroker.openConnection():" + E + "]" );
    newCon = null;
  }
  System.out.println( "[dbBroker.openConnection(): Success " );
  return newCon;
}


Listing 7: Getting a Connection

public static Connection pop(){
  synchronized( Broker ){
    dbConnection dbCon;
    for (;;){
      dbCon = Broker.getFreeConnection();
      if ( dbCon != null )
        break;

      if ( dbCon == null && Broker.dbList.size() != 0 ){
        try{
           Broker.wait();
        }catch(Exception E){}
      }
    }

    if ( Broker.dbList.size() == 0 ){
      System.out.println( "[dbBroker.pop: No free connections" );
      return null;
    }else{
      dbCon.setActive();
      return dbCon.Con;
    }
  }
}

Listing 8: giving the Connection Back

public static void push( Connection _Con ){
  if ( Broker == null || _Con == null ) return;

  synchronized (Broker){
    //-- Need to check the validity of the connection
    dbConnection dbCon = Broker.getConnection( _Con );
    if ( dbCon == null )  return;

    //-- Check the status of the connection
    try{
      dbCon.Con.commit();
      dbCon.Con.clearWarnings();
    }catch(Exception E){
      Broker.closeConnection( dbCon.Con );
    }

    if ( Broker.isClosed(dbCon.Con) ){
      dbCon.Con  = Broker.openConnection();
      if ( dbCon.Con == null ){
        System.out.println( "[dbBroker.push: Failed to reopen a dead connection]" );
        Broker.dbList.removeElement( dbCon );
        return;
      }
    }else{
      dbCon.setInActive();
    }
    Broker.notifyAll();
  }
}

Listing 9: Checking the Connections

public void run(){
  int debugCount=0;
  for (;;){
    debugCount++;
    if ( debugCount%30 == 0 ){
      Enumeration E = dbList.elements();
      dbConnection dbCon;
      while (E.hasMoreElements()){
        dbCon = (dbConnection)E.nextElement();
        System.out.println( "[dbBroker.run(): " + dbCon.toString() );
      }
    }

    try{
      Thread.currentThread().sleep( 60000 );
    }catch(Exception E1){}
  }
}

Listing 10: Setting Up the Connection Pool

public void service( HttpServletRequest _req, HttpServletResponse _res)
throws ServletException, IOException{
  dbBroker.getInstance();
  Connection newCon = dbBroker.pop();
  Statement Statmt;
  ResultSet Res;
  PrintWriter Out = new PrintWriter( _res.getOutputStream()   );

  try{
    Statmt = newCon.createStatement();
    Res    = Statmt.executeQuery( "SELECT * FROM USER_TABLE" );

    ResultSetMetaData RM = Res.getMetaData();

    while (Res.next()){
      String columnString = "";

      for ( int x=0; x < RM.getColumnCount(); x++ ){
        columnString += Res.getString(x+1) + " ";
      }

      Out.println( columnString );
    }

    Res.close();
    Statmt.close();
    dbBroker.push( newCon );
  }catch(SQLException E){
    System.out.println( "[jdbcServlet.service():" + E + "]" );
    _res.setStatus( HttpServletResponse.SC_NO_CONTENT );
    return;
  }

  Out.flush();
}


Build and execute query string


Listing 1:
import java.sql.*;
import com.f1j.util.*;
import com.f1j.ss.*;

public class dbManipulations {
  private java.sql.Connection m_sqlCon = null;
  private java.sql.Statement  m_stmt = null;

  public void retrieveAndPopulateDataFromDB(String strMonth,
    com.f1j.ss.Book book, int iSheet) throws Exception {
         
    String strQuery  = "Select orderid, name, volume, price  
    from orders, products ";
    String strQryCount = "Select count(*) from orders, products ";
    // Following are parameters specific to Oracle8I and the
    // machine it is used on
    // Change to reflect your configurations
    String strDriver = "oracle.jdbc.driver.OracleDriver";
    String strUrl    =  
    "jdbc:oracle:thin:@webtogo.domain.com:1521:domain";
    String strUser   = "scott";
    String strPassword = "tiger";
    int iSrcStartRow   = 21;
    int iRowCount      = 0;
         
    //connect to the database
    createConnection(strDriver, strUrl, strUser, strPassword);
         
    if (strMonth == null)   // default month name
      strMonth = "JANUARY";
    else
      strMonth=strMonth.toUpperCase();
         
    // Build and execute query string(s)
    String strBufWhere = "where upper(orders.month) = '"+strMonth+
                            "' and products.productid =
                               orders.productid";

    java.sql.ResultSet rs = queryRecords(strQryCount + str-
    BufWhere);
    if (rs != null && rs.next()) {
        iRowCount = rs.getInt(1);
        rs.close();
    }
    rs = queryRecords(strQuery + strBufWhere);

    try {            // Populate from ResultSet rs to
                     // Spreadsheet
      if (book != null) {
        Sheet sheet = book.getSheet(iSheet);
        com.f1j.jdbc.JDBC m_gridJDBC = new
        com.f1j.jdbc.JDBC(sheet);
        com.f1j.jdbc.JDBCQueryObj m_jdbcQryObj = new
        com.f1j.jdbc.JDBCQueryObj();
                 
        setFlagsJDBCQueryObject(iSrcStartRow, 0, m_jdbcQryObj);
        m_gridJDBC.populateGrid(rs, m_jdbcQryObj);
                 
        // Add total calculations to the bottom of the data  
        // and format
        int iTotalRow = iRowCount + iSrcStartRow;
                 
        sheet.setText(iTotalRow, 1, "TOTAL:");
        sheet.setFormula(iTotalRow, 2, "SUM(C"+iSrc-
        StartRow+":C"+iTotalRow+")");
        sheet.setFormula(iTotalRow, 4, "SUM(E"+iSrc-
        StartRow+":E"+iTotalRow+")");

sheet.copyRange(iTotalRow, 0, iTotalRow, 4,
                        sheet, iSrcStartRow-2, 0, iSrc-
                        StartRow-2, 4,
                        com.f1j.ss.Constants.eCopyFormats);      
        // format totals row
                                 
        // Add Revenue formula column to all retrieved rows
        int iSrcCol = 4;             //revenue column
        sheet.copyRange(iSrcStartRow+1, iSrcCol, iTotalRow-1,
        iSrcCol,
                        sheet, iSrcStartRow, iSrcCol, iSrc-
                        StartRow, iSrcCol,
                        com.f1j.ss.Constants.eCopyAll);
                 
        // Change Spreadsheet "Title" to correspond to
        // requested month
        String strTitle = sheet.getText(17, 0) + strMonth;
        sheet.setText(17, 0, strTitle);
                 
        // Change Chart range to correspond to the # of
        // records returned
        // The Chart takes its data from the defined names  
        // "chartData", "chartLegend"
        // So we will redefine them to reflect the amount of
        // data retrieved
        GRChart chart = (GRChart)book.getSheet(iSheet).get
        GRObject(3);
        chart.setTitle(strTitle);

        String sheetName = book.getSheet(iSheet).getName();              
        book.setDefinedName("chartData",
                            sheetName+"!$E$"+(iSrc-
                            StartRow+1)+":$E$"+iTotalRow,
                            0, 0);
        book.setDefinedName("chartLegend",
                            sheetName+"!$B$"+(iSrc-
                            StartRow+1)+":$B$"+iTotalRow,
                            0,0);
      }
    }
    finally {
      //close the database connections
      if (rs != null) rs.close();
      closeAll();
    }
  }

  private void setFlagsJDBCQueryObject (int iStartRow, int  
                                    iStartCol,
                                    com.f1j.jdbc.JDBC-
                                    QueryObj jdbcQryObj) {
    jdbcQryObj.setAutoColNames(false);   // don't return  
                                 // field name as col hdrs
    jdbcQryObj.setAutoColFormats(false); // format data
                                      // according to type
    jdbcQryObj.setAutoColWidths(true);   // autosize columns
    jdbcQryObj.setAutoMaxRC(false);      // don't change
                                 // max/min on spreadsheet
    jdbcQryObj.setStartRow(iStartRow);   // start row for
                                      // populating
    jdbcQryObj.setStartCol(iStartCol);   // start col for  
                                        // populating
    jdbcQryObj.setColNamesInRow(iStartRow); // put fields  
                                         // names in row
  }
     
  private void createConnection (String strDriverName,
    String strDatasource, String strUsername, String strPass-
    word) throws Exception {
             
    Driver d=(Driver)Class.forName(strDriverName).newInstance();
    DriverManager.registerDriver(d);
    m_sqlCon=DriverManager.getConnection(strDatasource,
    strUsername, strPassword);
    m_stmt=m_sqlCon.createStatement();
  }
     
  // Queries the database using the sqlStatment passed to it.  
  // It returns the resultset.
 
  private ResultSet queryRecords(String strSqlStmt) throws
  Exception {
    if (strSqlStmt != null)
      return m_stmt.executeQuery(strSqlStmt);
    else
      return (ResultSet)null;
  }

  private void closeAll() throws Exception {
    if (m_stmt != null)
      m_stmt.close();
    if (m_sqlCon != null)
      m_sqlCon.close();
  }
}

Listing 2: ExcelServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.f1j.swing.*;

public class Excel97Servlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServlet-
  Response response)
    throws ServletException, java.io.IOException  {
     
    ServletOutputStream out = response.getOutputStream();
    response.setContentType("application/vnd.ms-excel");
   
    // create a new Formula One workbook and lock it down.
    com.f1j.swing.JBook jbook = new com.f1j.swing.JBook();
    jbook.getLock();
   
    try {
      // read in the excel file we are using as a template
      // for this report
      jbook.read(getInitParameter("reportTemplate"));
           
      // Populate data from database into spreadsheet
      dbManipulations db = new dbManipulations();
      db.retrieveAndPopulateDataFromDB(request.getParame-
      ter("month"),
                                       jbook.getBook(),   0);
      // since we change the contents of the book we force a
      // recalc before writing the model.
      jbook.recalc();
      WriteExcel(out, jbook);
      out.close();
    }
    catch(Throwable e) {
      System.out.println(e.getMessage());
    }
    finally {
      jbook.releaseLock();
    }
  }
   
  // Formatting Excel data requires access to a "seekable" stream.
  // Since OutputStream is not  seekable, we create a temporary
  // file in excel format, then copy the data to the output stream.

  private void WriteExcel(OutputStream out,  
  com.f1j.swing.JBook jbook)
                         throws Exception {
    java.util.Date tempFileName = new java.util.Date();
    String tempFilePath = System.getProperty("user.dir") +
                          java.io.File.pathSeparator +
                          tempFileName.getTime();

    // write the book to a temporary file
    jbook.write(tempFilePath, jbook.eFileExcel97);

    File tempFile = new File(tempFilePath);
    FileInputStream tempfis = new FileInputStream(tempFile);

    byte buffer[] = new byte[1024];
    long totalBytesRead = 0;
    int  bytesRead = 0;

    while (totalBytesRead < tempFile.length()) {
        bytesRead = tempfis.read(buffer);
        totalBytesRead = totalBytesRead + bytesRead;
        out.write(buffer, 0, bytesRead);
    }
    tempfis.close();
    tempFile.delete();
  }
}

Listing 3: WebMail.java

// You will need the activation.jar and mail.jar standard
// java extensions to compile this code.

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

public class WebMail extends HttpServlet {
  private Session m_session;
  private String m_strFile;
  private String m_strTempFileName = "report.xls";
       
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    ServletContext ctxt = getServletContext();
    m_strFile = config.getInitParameter("report_template");
  }
       
  public void doGet(HttpServletRequest req, HttpServletRe-
  sponse res)
    throws ServletException, java.io.IOException {
             
    res.setContentType("text/html");
    java.io.PrintWriter writer = res.getWriter();
             
    //start the session
 // change the postoffice domain reference
 // throughout this code to match your system
    java.util.Properties properties = System.getProperties();
    properties.put("mail.smtp.host",  
    "postoffice.domain.com");

    //Connect to the store
    try {
      m_session = Session.getInstance(properties, null);
      Store store=m_session.getStore("imap");
      store.connect("postoffice.domain.com", "demo", "demo");
      sendMessage(req, res, writer);
    }
    catch (Exception e) {
      writer.println("Unable to connect to email account
      specified");
    }
  }
       
  private void sendMessage(HttpServletRequest req,
                           HttpServletResponse res,
                           java.io.PrintWriter writer)
    throws ServletException, java.io.IOException {
                 
    String strFrom = "demo@domain.com";
    String strTo = req.getParameter("to");
    String strMonth = req.getParameter("month").toUpperCase();
    String strSubject = "Sales Figures for the Month of " + strMonth;
    com.f1j.ss.Book book = new com.f1j.ss.Book();
             
    String strTempDir = null;
    try {
      strTempDir = createTemporaryDir();
      String strTempFile = strTempDir+java.io.File.separa-
      tor+m_strTempFileName;
                   
      if (strTempFile != null) {
        // Load worksheet template, retrieve data from data-
        // base and write to a temporary file.
        book.getLock();
        book.read(new java.io.FileInputStream(m_strFile));
        dbManipulations m_db = new dbManipulations();
        m_db. retrieveAndPopulateDataFromDB(strMonth, book, 0);
        book.write(book.getSheet(0), strTempFile, book.eFile-
        Excel97);
        book.releaseLock();
                         
        // build 2-part mail message and send it.
        MimeMessage message = new MimeMessage(m_session);
        Multipart mp        = new MimeMultipart();
        MimeBodyPart mbp1   = new MimeBodyPart();
        MimeBodyPart mbp2   = new MimeBodyPart();
                         
        message.setFrom(new InternetAddress(strFrom));
        message.setRecipients(Message.RecipientType.TO,
                               
        InternetAddress.parse(strTo));
        message.setSubject(strSubject);
        message.setContent(mp);
                         
        mbp1.setText("Report successfully sent");

        // create the file attachment part of the message
        mbp2.setDataHandler(new javax.activation.DataHandler(
             new javax.activation.FileDataSource(strTemp File)));
        mbp2.setFileName(m_strTempFileName);
                         
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
                             
        //send the message
        Transport.send(message);
        writer.println("<p> Sales report was sent to: " +  
        strTo + " </p>");
      }
      deleteTemporaryDir(strTempDir);
    }
    catch (Exception e) {
    writer.println("<p> " + e.getMessage() + " </p>");
    }
  }
       
  private String createTemporaryDir() {
    String strNewDir = System.getProperty("user.dir") +
    java.io.File.separator + (new java.util.Date()).getTime();
    java.io.File dir = new java.io.File(strNewDir);
    dir.mkdir();
    return strNewDir;
  }
       
  private synchronized void deleteTemporaryDir(String strTempDir) {
    java.io.File dir = new java.io.File(strTempDir);
    if (dir.exists()) {
      java.io.File file = new java.io.File(strTempDir +
      java.io.File.separator + m_strTempFileName);
      file.delete();
      dir.delete();
    }
  }
}

Listing 4: report.jsp

<%@ page import="dbManipulations" %>
<%
  // create a new formula one workbook
  com.f1j.swing.JBook jbook = new com.f1j.swing.JBook();

  jbook.getLock();
  try {
    java.io.File me=new java.io.File(request.getPathTranslated());
    jbook.read(me.getParent()+java.io.File.separator+"report_template.xls");
           
    dbManipulations db = new dbManipulations();
    db.retrieveAndPopulateDataFromDB(request.getParameter("month"),
                                     jbook.getBook(), 0);
           
    jbook.recalc();
    com.f1j.ss.HTMLWriter htmlWriter = new com.f1j.ss.HTMLWriter();
    htmlWriter.write(jbook.getBook(), 0, 17, 0, 0, 31, 4, out);
  } catch(Throwable e) { System.out.println("Error:  
  "+e.getMessage() ); }
  finally {
    jbook.releaseLock();
  }
%>

The remote interface of the stateless session bean MiddleBean.java


Listing 1A: The remote interface of the stateless session bean MiddleBean.java

package sameer.ejb;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface Middle extends EJBObject {
  public void doTransaction (String customerName,String password,int age) throws RemoteException;

}

Listing 1B: The home interface of the stateless  session bean MiddleBean.java

package sameer.ejb;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface MiddleHome extends EJBHome {
  Middle create() throws CreateException, RemoteException;
}

Listing 1C: The stateless session bean MiddleBean.java

package sameer.ejb;

import javax.ejb.*;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.naming.*;
import java.util.*;
import java.sql.*;

public class MiddleBean implements SessionBean {

  public void ejbActivate() {}
  public void ejbRemove() {}
  public void ejbPassivate(){}
  public void setSessionContext(SessionContext ctx) {}
  public void ejbCreate () throws CreateException {}


  public void doTransaction(String customerName, String pass-
  word,int age)
throws MyException{
 try{
  Context ctx = new InitialContext();
  TranstestHome home = (TranstestHome)  
    ctx.lookup("ejb.TranstestHome");
  Transtest bean = home.create();
bean.putUser("Sameer","word");
       bean.putAge("Sameer",10);

   }catch(Exception e){
  throw new MyException("an exception occured" +e);
}
  }


}

Listing 2A: The remote interface of the stateless session bean TranstestBean

package sameer.ejb;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface Transtest extends EJBObject {

public void putUser (String customerName,String password)
throws RemoteException,MyException;
  public void putAge (String customerName,int age) throws RemoteException,MyException;
}

Listing 2B: The home interface of the stateless session bean TranstestBean

package sameer.ejb;

import javax.ejb.*;
import java.rmi.RemoteException;

public interface TranstestHome extends EJBHome {
  Transtest create() throws CreateException, RemoteException;
}

Listing 2C: The stateless session bean TranstestBean

package sameer.ejb;

import javax.ejb.*;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.*;
import java.sql.*;
public class TranstestBean implements SessionBean {

  public void ejbActivate() {}
  public void ejbRemove() {}
  public void ejbPassivate(){}
  public void setSessionContext(SessionContext ctx) {}

public void ejbCreate () throws CreateException {}


  public void putUser(String customerName, String password)  
  throws MyException{
try{
String str = "INSERT INTO USERTABLE (name, pwd) VALUES ('" + customerName + "','" +
  password +"')";
  System.out.println ("Executing stmt: " + str);
  new weblogic.jdbc.jts.Driver();
          Connection   conn=DriverManager.getConnection("jdbc:weblogic:jts:demoPool")  ;
      Statement stmt=conn.createStatement();
      int rs=stmt.executeUpdate(str);
      System.out.println(">>>>Username/Pwd insert succeeded  
      for "+ customerName +"
   and password "+password);

throw new MyException(); // delibrately throw an applica-
  tion exception

}catch(SQLException se){
throw new MyException("There was an exceptin "+se);
}
}

  public void putAge(String customerName,int age) throws
  MyException {
  try{
 String str ="INSERT INTO AGETABLE (name, age) VALUES ('" +  
   customerName + "',"
  + age +")";
 System.out.println ("Executing stmt: " + str);
// Class.forName("weblogic.jdbc.jts.Driver");
 new weblogic.jdbc.jts.Driver();
 Connection conn=DriverManager.getConnection("jdbc:weblog-
   ic:jts:demoPool");
 Statement stmt=conn.createStatement();
 int rs=stmt.executeUpdate(str);
 System.out.println(">>>>Username/Age insert succeeded for
   "+ customerName +"
  and age "+age);
}catch(SQLException se){
throw new MyException("There was an exceptin "+se);
}
  }

}

Listing 3: The application exception class that is deliberately thrown

package sameer.ejb;

public class MyException extends Exception {
  public MyException() {}
  public MyException(String message) {
 super(message);
 }
}

Listing 4: The client for the sessionbean MiddleBean

package sameer.ejb;

import javax.ejb.*;
import javax.naming.*;
import java.rmi.RemoteException;
import java.util.*;


public class Client {
  static String url = "t3://localhost:7001";
  static String user= null;
  static String password= null;

public static void main(String[] args) throws Exception {
      Context ctx = getInitialContext();
      MiddleHome home = (MiddleHome) ctx.lookup("ejb.MiddleHome");
      Middle bean = home.create();
      bean.doTransaction("Sameer","word",26);
  }

  public static Context getInitialContext() throws Exception {
    Hashtable h = new Hashtable();

h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    h.put(Context.PROVIDER_URL, url);
    return new InitialContext(h);
  }
}

HashMap


Listing 1:

private static Connection dbConnection;
  private static HashMap companyMap = new HashMap();
  private static StringBuffer tempBuffer;

  private static final String insertPortfolioCompaniesSQL;
  static{
    tempBuffer = new StringBuffer("INSERT INTO Portfolio_Com-
    panies ");
    tempBuffer.append("(portfolio_id,business_entity_id,
    nbr_shares_held) ");
    tempBuffer.append("VALUES(?,?,?)");
    insertPortfolioCompaniesSQL = tempBuffer.toString();
  }
  private void insertPortfolioCompanies() throws SQLException {
    PreparedStatement pstmt = null;
    try {
      pstmt = dbConnection.prepareStatement(insertPortfolio-
      CompaniesSQL);
      if(companyMap.isEmpty()){
        Collection companyCollection = companyMap.values();
        for(Iterator i = companyCollection.iterator(); i.has-
        Next(); ){
          PortfolioConstituent pc =
          (PortfolioConstituent)i.next();
          pstmt.setDouble(1,pc.getPortfolioID());
          pstmt.setDouble(2,pc.getCompanyID());
          pstmt.setDouble(3,pc.getShares());

          pstmt.execute();
        }
        pstmt.close();
        dbConnection.commit();
      }
    } finally { JDBCUtilities.close(pstmt);  }
  }


Listing 2:

static public void close (ResultSet rs) {
    try { if (rs!=null) rs.close(); } catch (Exception e) {}
    }

  //  Works for PreparedStatement also since it extends
  //  Statement.
  static public void close (Statement stmt) {
    try { if (stmt!=null) stmt.close(); } catch (Exception e)   {}
    }

  static public void close (java.sql.Connection conn) {
    try { if (conn!=null) conn.close(); } catch (Exception e) {}
    }

  static public void close (dvt.util.db.Connection conn) {
    try { if (conn!=null) conn.close(); } catch (Exception e) {}
    }

Listing 3:

package dvt.util.db;

import java.lang.*;
import java.sql.*;
import oracle.jdbc.driver.*;

/**
 * Connection represents a generic database connection.
 *
 * @author Derek C. Ashmore
 * @version 1.0
 *
 */

public class Connection {

    public static final String ORACLE_8I = "8I";
    public static final String CLOUDSCAPE = "CLOUDSCAPE";
    public static final String ORACLE_LITE = "ORACLE_LITE";
    public static final String GENERIC = "GENERIC"

public static final String CLOUDSCAPE_DRIVER =  
    "COM.cloudscape.core.JDBCDriver";
    public static final String ORACLE_LITE_DRIVER =
    "oracle.lite.poljdbc.POLJDBCDriver";
    public static final String ORACLE_8I_DRIVER =
    "oracle.jdbc.driver.OracleDriver";

    /**
     * Registers the database driver and obtains the speci-
     * fied database connection.
     *
     * @param JDBCDriver
     * @param connectString
     * @param localUserId
     * @param localPassword
     */
    public Connection(   String jdbcDriverName,
                                String connectString,
                                String localUserId,
                                String localPassword) {

        setUserId(localUserId);
        setPassword(localPassword);

        if (jdbcDriverName.equals(ORACLE_LITE_DRIVER))
            platform = ORACLE_LITE;
        else if (jdbcDriverName.equals(CLOUDSCAPE_DRIVER))
            platform = CLOUDSCAPE;
        else if (jdbcDriverName.equals(ORACLE_8i_DRIVER))
            platform = ORACLE_8i;
        else platform = GENERIC;

        registerDBDriver(jdbcDriverName);
        currentConnection = getConnection(connectString, con-
        nectString);
    }

    /**
     * Registers the database drivers.
     */

    private void registerDBDriver(String jdbcDriverName) {
        try {
            Class.forName( jdbcDriverName );
            this.setDriverRegistered( true );
        }
        catch (Exception DBError) {
            System.out.println(DBError.getMessage());
            DBError.printStackTrace();
        }
    }

    /**
     * Prepares a SQL statement.
     *
     * @param localSQLString
     * @exception java.sql.SQLException
     */
   
    public PreparedStatement prepareStatement(String local-
    SQLString)  throws SQLException {
        return currentConnection.prepareStatement(localSQL-
        String);
    }

    /**
     * Returns the current Oracle database connection.
     */
   
    private java.sql.Connection getConnection(String jdbc-
    DriverName, String connectString) {

        if (isConnected()) return currentConnection;
        if (! isDriverRegistered())  registerDBDriver(jdbc
        DriverName);
       
        try {
            currentConnection = DriverManager.getConnec-
            tion(connectString,
                        userId, password);
            if (platform.equals(ORACLE_8I))   {
                OracleConnection oConnect = (OracleConnec-
                tion) currentConnection;
                oConnect.setDefaultRowPrefetch( default
                PrefetchSize );
                oConnect.setDefaultExecuteBatch( default
                WriteBatchSize );
                Statement alterDateFormat = currentConnec-
                tion.createStatement();
                alterDateFormat.execute("alter session set  
                NLS_DATE_FORMAT = 'YYYYMMDDHHMISS'");
                }
            currentConnection.setAutoCommit( defaultAutoCom-
            mitSetting );

            this.setConnected(true);
        }
        catch (SQLException DBError) {
            System.out.println(DBError.getMessage());
            DBError.printStackTrace();  
        }
        return currentConnection;
    }

    public java.sql.Connection getConnection()   { return  
    currentConnection; }

    /**
     * Provides the user id associated with the current
     database connection.
     */

    public String getUserId() {
        return userId;
    }

    /**
     * Sets the user id used to obtain the database connection.
     *
     * @param localUserId
     */
   
    private void setUserId(String localUserId) {
        userId = localUserId;
    }

    /**
     * Provides the password used to obtain the database
       connection.
     */
   
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password used to obtain the database connection.
     *
     * @param localPassword
     */
   
    private void setPassword(String localPassword) {
        password = localPassword;
    }

    /**
     * Provides information as to whether or not database
     * driver registration has occurred.
     */
   
    private boolean isDriverRegistered() {
        return driverRegistered;
    }

    /**
     * Issues a database commit to save all pending changes
     * to the database.
     */
   
    public void commit()    throws SQLException {
        currentConnection.commit();
    }
   
    /**
     * Issues a database rollback to abort all pending  
     * changes to the database.
     */
   
    public void rollback()    throws SQLException {
        currentConnection.rollback();
    }

    /**
     * Issues a database disconnect.
     */
   
    public void close()    throws SQLException {
        currentConnection.close();
    }

    /**
     * Issues a database disconnect and closes a given
     * statement
     * (provided for programatic convenience -- doesn't logically
     *  belong here).
     *
     * @param PreparedStatement
     */

    public void close(PreparedStatement preparedStatement)    
    throws SQLException {
        try  {
            preparedStatement.close();
            }
        catch (SQLException e)  {
            e.printStackTrace();
            }
        this.close();
    }

    /**
     * Issues a database disconnect and closes a given
     * statement and result set (provided for programatic
     * convenience -- doesn't logically belong here).
     *
     * @param PreparedStatement
     * @param ResultSet
     */

    public void close(PreparedStatement preparedStatement,
    ResultSet resultSet)    throws SQLException {
        try  {
            resultSet.close();
            }
        catch (SQLException e)  {
            e.printStackTrace();
            }
        this.close(preparedStatement);
    }

   
    /**
     * Records registration status of database drivers.
     *
     * @param LocalDriverRegistered
     */
   
    private void setDriverRegistered(boolean LocalDriverReg-
    istered) {
        driverRegistered = LocalDriverRegistered;
    }

    /**
     * Provides information about current database connection
     * status.
     */
   
    public boolean isConnected() {
        return connected;
    }

    /**
     * Sets database connection status information.
     *
     * @param LocalConnected
     */
   
    private void setConnected(boolean LocalConnected) {
        connected = LocalConnected;
    }

    /**
     * Sets the array size used for select statements.
     *
     * @param arraySize
     */

    public void setPrefetchSize(int arraySize) throws SQLEx-
    ception {
      if (platform.equals(ORACLE_8i))  {
        OracleConnection oConnection = (OracleConnection)  
        currentConnection;
        oConnection.setDefaultRowPrefetch( arraySize );
        }
    }

    /**
     * Provides the array size used for select statements.
     *
     */

    public int getPrefetchSize() throws SQLException {
      if (platform.equals(ORACLE_8i))  {
        OracleConnection oConnection = (OracleConnection)  
        currentConnection;
        return oConnection.getDefaultRowPrefetch();
        }
      else return -1;
    }

    /**
     * Sets the array size used for update, insert, and  
     * delete statements.
     *
     * @param arraySize
     */

    public void setWriteBatchSize(int arraySize) throws  
    SQLException {
      if (platform.equals(ORACLE_8i))  {
        OracleConnection oConnection = (OracleConnection)  
        currentConnection;
        oConnection.setDefaultExecuteBatch( arraySize );
        }
    }

    /**
     * Provides the array size used for update, insert, and
     * delete statements.
     *
     */

    public int getWriteBatchSize() throws SQLException {
      if (platform.equals(ORACLE_8i))  {
        OracleConnection oConnection = (OracleConnection)  
        currentConnection;
        return oConnection.getDefaultExecuteBatch();
        }
      else return -1;
    }

    /**
     * Sets the AutoCommit specification for the connection.  
     * Set to true to
     * have commits automatically issued.  Set to false to  
     * handle commits
     * and rollbacks manually.
     *
     * @param autoCommitInd
     */

    public void setAutoCommitSetting(boolean autoCommitInd)  
    throws SQLException {
        currentConnection.setAutoCommit( autoCommitInd );
    }

    /**
     * Provides the AutoCommit specification for the connec-
     * tion.  True means that commits are automatically
     * issued.  False means that commits and rollbacks are
     * handled manually.
     *
     */

    public boolean getAutoCommitSetting() throws SQLException {
        return currentConnection.getAutoCommit();
    }

    /**
     * Provides database platform used for the connection.
     */
    public String getPlatform()   {  return platform; }

    /**
     * User ID used to obtain database connection.
     */
    private String userId;

    /**
     * Password used to obtain database connection.
     */
    private String password;

    /**
     * Prefetch size (select array processing batch size)
     * for database connection.
     */
    private int defaultPrefetchSize = 100;

    /**
     * Default update Batch size (number of write DML state
     * ments to queue) for database connection.
     */
    private int defaultWriteBatchSize = 20;

    /**
     * Auto Commit mode for database connection.
     */

     private boolean defaultAutoCommitSetting = false;

    /**
     * Indicates database driver registration status.
     */
    private boolean driverRegistered;

    /**
     * Indicates last known database connection status.
     */
    private boolean connected;

    /**
     * Contains JDBC connection information.
     */
    private java.sql.Connection currentConnection = null;

    /**
     * Contains JDBC connection information.
     */
    private String platform = null;
}

Task implements


Listing 1:


public abstract class Task implements java.io.Serializable
{
...
}

Listing 2:

struct Task
{
// Add information specific to the task
};

Listing 3:

public abstract class Task implements javax.ejb.EntityBean
{
...
}

Listing 4:

import java.rmi.*;
import java.rmi.server.*;
public abstract class Handler extends Thread
{

protected abstract void handle(Task task) throws Exception;
   public void run()
   {
      try
      {
         Scheduler scheduler = (Scheduler)  Naming.lookup("rmi://localhost/scheduler");
         while (true)
         {
            Task[] tasks = scheduler.getTasks(10);

            for (int i=0 ; i<tasks.length ; i++)
            {
               try
               {
                  handle(tasks[i]);
               }
               catch (Exception handleException)
               {
                  handleException.printStackTrace();
               }
            }
            // Sleep for five seconds
            try { sleep(5000); } catch (Exception sleepException) { }
         } 
      } 
      catch (Exception e)
      {
            e.printStackTrace();
      } 
   }  
}


Listing 5:

import java.rmi.*;
public interface Scheduler extends Remote
{
   // Add a Task to the queue
   public void addTasks(Task[] task) throws RemoteException;

   // Get tasks
   public Task[] getTasks(int max) throws RemoteException;
   
   // Indicate completion
   public void complete(Task[] task) throws RemoteException;
}

Listing 6:

import java.rmi.*;
import java.rmi.server.*;
import java.sql.*;
public class UpdateHandler extends Handler
{
   private Connection connection_ = null;
   public UpdateHandler() throws Exception
   {
      Class.forName(driver);
      connection_ = DriverManager.getConnection(url, user, password);
   }
   protected void handle(Task task) throws Exception
   {
      if (task instanceof UpdateTask)
      {
         Exception exception = null;
         UpdateTask updateTask = (UpdateTask) task;
         Statement stmt = -znull;
         try
         {
            stmt = connection_.createStatement();
            String sql = updateTask.getSQL();
            stmt.executeUpdate(sql);
         }
         catch (Exception e)
         {
            exception = e;
         }
         finally
         {
            try
            {
               if (stmt != null)
                  stmt.close();
            }
            catch (Exception fe)
            {
            }
         }
      }
   }
}