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)
            {
            }
         }
      }
   }
}

ServletBase


     Servlet to Servlet Communication
   
     Listing 1: ServletBase
     public class ServletBase extends HttpServlet{
     static Connection databaseConnection = null;
     public void init(ServletConfig _config) throws ServletException{
     super.init(_config);
     if ( databaseConnection == null )
     //- Open up the database connection
     }
     protected boolean isLoggedOn( String _username ){
     return true;
     }
     protected boolean logUserOn( String _username ){
     return true;
     }
     }
     Listing 2: Using the NewSerletBase Class
     public class logonServlet extends ServletBase{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     if ( isLoggedOn( _req.getParameter(ÒUSERNAMEÓ) ){
     //- Display a message indicating they are already logged on
     }else{
     logUserOn( _req.getParameter(ÒUSERNAMEÓ) );
     }
     }
     }
     Listing 3: Storing an Object
     public class logonServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext thisContext = getServletContext();
     //-- Assume some method creates a new connection class
     Connection newConnection = createConnection();
     thisContext.setAttribute( Òdatabase.connectionÓ, newConnection );
     //-- Return some output to the client
     }
     }
     Listing 4: retrieving an Object
     public class logoffServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext thisContext = getServletContext();
     //-- Assume some method creates a new connection class
     Connection newConnection = thisContext.getAttribute(
     Òdatabase.connectionÓ);
     if ( newConnection == null )
     //- Database has not been opened yet
     //-- Return some output to the client
     }
     }
     Listing 5: Looking at All the Objects
     public class allServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext thisContext = getServletContext();
     //-- Assume some method creates a new Connection class
     Enumeration E = thisContext.getAttributeNames();
     while ( E.hasMoreElements() ){
     String name = (String)E.nextElement();
     System.out.println( "Object: " + name );
     }
     }
     }
     Listing 6: Retrieving Remote Contexts
     public class otherServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext otherContext =
     getServletContext(Òhttp://<otherdomain>/servlet/allServletÓ);
     //-- Assume some method creates a new Connection class
     Enumeration E = otherContext.getAttributeNames();
     while ( E.hasMoreElements() ){
     String name = (String)E.nextElement();
     System.out.println( "Object: " + name );
     }
     }
     }
     Listing 7: Forwarding a Request
     public class forwardServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext xt = getServletContext();
     RequestDispatcher xyzServlet =
     xt.getRequestDispatcher(Òhttp://<domain>/servlet/xyzServletÓ);
     //- Do any preliminary processing
     _req.setAttribute( Òdatabase.resultsÓ, new Results() );
     xyzServlet.forward( _req, _res );
     }
     }
     Listing 8: Inserting Content
     public class insertServlet extends HttpServlet{
     public void service(HttpServletRequest _req, HttpServletRe-
     sponse _res) throws ServletException{
     ServletContext xt = getServletContext();
     RequestDispatcher xyzServlet =
     xt.getRequestDispatcher(Òhttp://<domain>/servlet/xyzServletÓ);
     PrintWriter Out = _res.getWriter();
     Out.println( ÒThis is from the insertServlet Ò );
     for(int x=0; x < 10; x++ )
     xyzServlet.insert( _req, _res );
     Out.println( ÒThis is the end of the print servlet Ò );
     }
     }

Implementing Business Rules in Java


  

     Listing 1
     public void correlateAlarm ( Alarm alarm )
     {
     //Related Alarms
     //When a switch raises an equipment failure alarm ignore all
     //communication failure alarms on the associated port.
     if ((alarm.type == Alarm.Type.CommunicationFailure)
     && (alarm.managedObject.type ==
     NetworkElement.Type.Port))
     {
     // search for Equip failure on Switch
     AlarmList alarms = GetHistoryAlarmList();
     for (Alarm a = alarms.firstElement();
     alarms.hasMoreElements(); a = alarms.nextElement())
     if ((a.type == Alarm.Type.EquipmentFailure)
     && (alarm.managedObject.type == NetworkEle-
     ment.Type.Switch)
     && (a.managedObject.node == alarm.managedObject)) {
     alarm.terminate(
     "Terminated Communication Failure on Port
     due to Equipment Failure on the Switch " +
     alarm.managedObject.id);
     return;
     }
     }
     //Maintenance Activity Scheduled
     //When maintenance activity has been scheduled on a net-
     //work element ignore all alarms raised on this piece
     //of hardware between the maintenance start and end time.
     MaintenanceActivityList activities = GetMaintenanceActiv-
     ityList(alarm.managedObject);
     for (MaintenanceActivity maintenance =
     activities.firstElement();
     activities.hasMoreElements(); maintenance = activi-
     ties.nextElement())
     if ((alarm.time >= maintenance.startTime)
     && (alarm.time <= maintenance.endTime) {
     alarm.terminate("Terminated due to a maintenance
     activity on "
     + alarm.managedObject.id);
     return;
     }
     // Critical Alarms on Sensitive Devices
     // When more than 15 alarms are detected on a Network Element,
     // notify the Network Operator by Pager.
     // When more than 5 alarms are detected on a Switch,
     // notify the Network Operator by Pager.
     AlarmList alarms = GetHistoryAlarmList();
     int count = 0;
     int countOnSwitch = 0;
     for (Alarm a = alarms.firstElement();
     alarms.hasMoreElements(); a = alarms.nextElement()) {
     if (alarm.managedObject == a.managedObject) {
     count++;
     if (alarm.managedObject.type ==
     NetworkElement.Type.Switch)
     countOnSwitch++;
     }
     }
     if (count > 15)
     network.pageOperator("More than 15 alarms on the NE " +
     alarm.managedObject.id);
     else if (countOnSwitch > 5)
     network.pageOperator("More than 5 alarms on the Switch " +
     alarm.managedObject.id);
     } // public void correlateAlarm
     Listing 2
     //Related Alarms
     //When a switch raises an equipment failure alarm ignore all
     //communication failure alarms on the associated port.
     rule Port_CommunicationFailure_due_to_Switch_EquipmentFailure
     {
     priority = maximum;
     when
     {
     ?alarm: Alarm(type == Alarm.Type.EquipmentFailure);
     ?switch: Switch() from ?alarm.managedObject;
     ?comm: Alarm(type == Alarm.Type.CommunicationFailure);
     Port(node == ?switch) from ?comm.managedObject;
     }
     then
     {
     modify ?comm
     {
     terminate("Terminated Communication Failure on Port due
     to Equipment Failure on a Switch");
     }
     }
     };
     //Maintenance Activity Scheduled
     //When maintenance activity has been scheduled on a network
     //element ignore all alarms raised on this piece of hardware //between
     the maintenance start and end time.
     rule Terminate_Alarms_During_Maintenance
     {
     priority = high;
     when
     {
     ?maintenance: MaintenanceActivity();
     ?alarm: Alarm(managedObject == ?maintenance.managedObject ; time >=
     ?maintenance.startTime ; time <= ?maintenance.endTime);
     }
     then
     {
     modify ?alarm
     {
     terminate("Terminated due to a maintenance window on " +
     ?maintenance.managedObject.id);
     }
     }
     };
     // Critical Alarms on Sensitive Devices
     // When more than 15 alarms are detected on a Network Element,
     // notify the Network Operator by Pager.
     // When more than 5 alarms are detected on a Switch,
     // notify the Network Operator by Pager.
     rule Page_Operator_When_Critical_Alarm_On_Network_Element
     {
     when
     {
     ?n: Network();
     ?networkElement: NetworkElement();
     collect Alarm(managedObject == ?networkElement)
     where (size() >15);
     }
     then
     {
     ?n.pageOperator("More that 15 alarms on the NE " + ?net
     workElement.id);
     }
     };
     rule Page_Operator_When_Critical_Alarm_On_Switch
     {
     when
     {
     ?n: Network();
     ?switch: Switch();
     collect Alarm(managedObject == ?switch)
     where (size() > 5);
     }
     then
     {
     ?n.pageOperator("More that 5 alarms on the Switch" + ?switch.id);
     }
     };