Index: src/edu/ucsb/nceas/metacat/DBValidate.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBValidate.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBValidate.java	(revision 1217)
@@ -96,7 +96,7 @@
   }
 
   /** Construct a new validation object using a database entity resolver */
-  public DBValidate(String parserName, Connection conn) {
+  public DBValidate(String parserName, DBConnection conn) {
     this(parserName);
 
     DBEntityResolver dbresolver = new DBEntityResolver(conn);
@@ -208,8 +208,11 @@
     String doc = args[0];
 
     MetaCatUtil util = new MetaCatUtil();
+    DBConnection conn = null;
+    int serailNumber = -1;
     try {
-      Connection conn = util.openDBConnection();
+      conn = DBConnectionPool.getDBConnection("DBValidate.main");
+      serailNumber = conn.getCheckOutSerialNumber();
   
       DBValidate gxv = new DBValidate(util.getOption("saxparser"), conn);
       if (gxv.validate(doc)) {
@@ -219,9 +222,11 @@
       }
     } catch (SQLException e) {
       System.out.println("<error>Couldn't open database connection.</error>");
-    } catch (ClassNotFoundException e) {
-      System.out.println("<error>Couldn't open database connection.</error>");
-    }
+    } 
+    finally
+    {
+      DBConnectionPool.returnDBConnection(conn, serailNumber);
+    }//finally
   }
 
     
Index: src/edu/ucsb/nceas/metacat/DBConnectionPool.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBConnectionPool.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBConnectionPool.java	(revision 1217)
@@ -78,6 +78,9 @@
   final static long CYCLETIMEOFDBCONNECTION = 
                Long.parseLong(MetaCatUtil.getOption("cycleTimeOfDBConnection"));
                
+  //the number for trying to check out a connection in the pool in 
+  //getDBConnection method
+  final static int LIMIT = 2;
   
   final static int FREE = 0; //status of a connection
   final static int BUSY = 1; //statis of a connection
@@ -185,12 +188,27 @@
                                                 throws SQLException
   {
     DBConnection db = null;
-    MetaCatUtil.debugMessage("Try to checking out connection...", 10);    
-    //try every DBConnection in the pool
-  
-      for (int i=0; i<connectionPool.size(); i++)
+    int random = 0; //random number
+    int index = 0; //index
+    int size = 0; //size of connection pool
+    MetaCatUtil.debugMessage("Try to checking out connection...", 45);
+    size = connectionPool.size();
+    MetaCatUtil.debugMessage("size of connection pool: "+size, 45);
+    
+     //try every DBConnection in the pool
+    //every DBConnection will be try LIMITE times
+    for (int j=0 ; j<LIMIT; j++)
+    {
+       //create a random number as the started index for connection pool
+      //So that the connection ofindex of 0 wouldn't be a the heaviest user
+      random = (new Double (Math.random()*100)).intValue();
+      for (int i=0; i<size; i++)
       {
-        db = (DBConnection) connectionPool.elementAt(i);
+        index =(i+random)%size;
+        db = (DBConnection) connectionPool.elementAt(index);
+        MetaCatUtil.debugMessage("Index: "+index, 45);
+        MetaCatUtil.debugMessage("Tag: "+db.getTag(), 45);
+        MetaCatUtil.debugMessage("Status: "+db.getStatus(), 45);
         //check if the connection is free
         if (db.getStatus()==FREE)
         {
@@ -208,11 +226,13 @@
             db.setCheckOutMethodName(methodName);
             //debug message
             MetaCatUtil.debugMessage("The connection is checked out: "
-                                       +db.getTag(), 20);
-            MetaCatUtil.debugMessage("The age is "+db.getAge(), 25);
-            MetaCatUtil.debugMessage("The usage is "+db.getUsageCount(), 25);
+                                       +db.getTag(), 35);
+            MetaCatUtil.debugMessage("The method for checking is: " 
+                                              +db.getCheckOutMethodName(), 35);
+            MetaCatUtil.debugMessage("The age is "+db.getAge(), 40);
+            MetaCatUtil.debugMessage("The usage is "+db.getUsageCount(), 40);
             MetaCatUtil.debugMessage("The conection time it has: "
-                                                +db.getConnectionTime(), 25);
+                                                +db.getConnectionTime(), 40);
             //set check out time
             db.setCheckOutTime(System.currentTimeMillis());
             //check it out
@@ -223,21 +243,21 @@
             //close this DBConnection
             db.close();
             //remove it form connection pool
-            connectionPool.remove(i);
+            connectionPool.remove(index);
             //insert a new DBConnection to same palace
             db = new DBConnection();
-            connectionPool.insertElementAt(db, i);
+            connectionPool.insertElementAt(db, index);
           }//else
         }//if
       }//for
+    }//for
     
-    
     //if couldn't get a connection, we should increase DBConnection pool
     //if the connection pool size is less than maximum connection number
-    int poolSize = connectionPool.size(); 
-    if ( poolSize < MAXIMUMCONNECTIONNUMBER )
+   
+    if ( size < MAXIMUMCONNECTIONNUMBER )
     {
-       if ((poolSize+INCREASECONNECTIONNUMBER) < MAXIMUMCONNECTIONNUMBER)
+       if ((size+INCREASECONNECTIONNUMBER) < MAXIMUMCONNECTIONNUMBER)
        { 
          //if we can create INCREASECONNECTIONNUMBER of new DBConnection
          //add to connection pool
@@ -251,7 +271,7 @@
        {
          //There is no enough room to increase INCREASECONNECTIONNUMBER 
          //we create new DBCoonection to Maximum connection number
-         for (int i= poolSize+1; i<= MAXIMUMCONNECTIONNUMBER; i++)
+         for (int i= size+1; i<= MAXIMUMCONNECTIONNUMBER; i++)
          {
            DBConnection dbConn = new DBConnection();
            connectionPool.add(dbConn);
@@ -261,115 +281,35 @@
     }//if
     else
     {
-      throw new SQLException("The maximum of " +MAXIMUMCONNECTIONNUMBER + 
+      /*throw new SQLException("The maximum of " +MAXIMUMCONNECTIONNUMBER + 
                             " open db connections is reached." +
                             " New db connection to MetaCat" +
-                            " cannot be established.");
-      
-    }//else
-    
-    //recursive to get new connection    
-    return getDBConnection();
-  }//getDBConnection
-
-  /**
-   * Method to get a DBConnection in connection pool
-   * 1) try to get a DBConnection from DBConnection pool
-   * 2) if 1) failed, then check the size of pool. If the size reach the
-   *    maximum number of connection, throw a exception: couldn't get one
-   * 3) If the size is less than the maximum number of connectio, create some
-   *    new connections and recursive get one
-   */
-  public static synchronized DBConnection getDBConnection() throws SQLException
-  {
-    DBConnection db = null;
-    MetaCatUtil.debugMessage("Try to checking out connection...", 10);    
-    //try every DBConnection in the pool
-  
-      for (int i=0; i<connectionPool.size(); i++)
-      {
-        db = (DBConnection) connectionPool.elementAt(i);
-        //check if the connection is free
-        if (db.getStatus()==FREE)
-        {
-          //If this connection is good, return this DBConnection
-          if (validateDBConnection(db))
-          {
-            
-            //set this DBConnection status
-            db.setStatus(BUSY);
-            //increase checkout serial number
-            db.increaseCheckOutSerialNumber(1);
-            //increase one usageCount
-            db.increaseUsageCount(1);
-            //debug message
-            MetaCatUtil.debugMessage("The connection is checked out: "
-                                       +db.getTag(), 25);
-            MetaCatUtil.debugMessage("The age is "+db.getAge(), 25);
-            MetaCatUtil.debugMessage("The usage is "+db.getUsageCount(), 25);
-            MetaCatUtil.debugMessage("The conection time it has: "
-                                                +db.getConnectionTime(), 25);
-            //set check out time
-            db.setCheckOutTime(System.currentTimeMillis());
-            //check it out
-            return db;
-          }//if
-          else//The DBConnection has some problem
-          {
-            //close this DBConnection
-            db.close();
-            //remove it form connection pool
-            connectionPool.remove(i);
-            //insert a new DBConnection to same palace
-            db = new DBConnection();
-            connectionPool.insertElementAt(db, i);
-          }//else
-        }//if
-      }//for
-    
-    
-    //if couldn't get a connection, we should increase DBConnection pool
-    //if the connection pool size is less than maximum connection number
-    int poolSize = connectionPool.size(); 
-    if ( poolSize < MAXIMUMCONNECTIONNUMBER )
-    {
-       if ((poolSize+INCREASECONNECTIONNUMBER) < MAXIMUMCONNECTIONNUMBER)
-       { 
-         //if we can create INCREASECONNECTIONNUMBER of new DBConnection
-         //add to connection pool
-         for ( int i=0; i<INCREASECONNECTIONNUMBER; i++)
-         {
-           DBConnection dbConn = new DBConnection();
-           connectionPool.add(dbConn);
-         }//for
-       }//if
-       else
-       {
-         //There is no enough room to increase INCREASECONNECTIONNUMBER 
-         //we create new DBCoonection to Maximum connection number
-         for (int i= poolSize+1; i<= MAXIMUMCONNECTIONNUMBER; i++)
-         {
-           DBConnection dbConn = new DBConnection();
-           connectionPool.add(dbConn);
-         }//for
-       }//else
-   
-    }//if
-    else
-    {
-      throw new SQLException("The maximum of " +MAXIMUMCONNECTIONNUMBER + 
+                            " cannot be established.");*/
+       MetaCatUtil.debugMessage("The maximum of " +MAXIMUMCONNECTIONNUMBER + 
                             " open db connections is reached." +
                             " New db connection to MetaCat" +
-                            " cannot be established.");
+                            " cannot be established.", 1);
+       return null;
+       //if couldn't get a connection, sleep 20 seconds and try again.
+       /*try
+       {
+         System.out.println("sleep");
+         Thread.sleep(2000);
+       }
+       catch (Exception e)
+       {
+       }*/
+         
       
     }//else
     
     //recursive to get new connection    
-    return getDBConnection();
+    return getDBConnection(methodName); 
   }//getDBConnection
+
+ 
   
   
-  
   /** 
    * Method to check if a db connection works fine or not
    * Check points include:
@@ -382,8 +322,8 @@
    */
   private static boolean validateDBConnection (DBConnection dbConn)
   {
-    Connection conn = null;
     
+    
     //Check if the DBConnection usageCount if it is too many
     if (dbConn.getUsageCount() >= MAXIMUMUSAGENUMBER )
     {
@@ -408,11 +348,10 @@
     }
     
     //Try to run a simple query
-    conn = dbConn.getConnections();
     try
     {
       long startTime=System.currentTimeMillis();
-      conn.getMetaData();
+      DatabaseMetaData metaData = dbConn.getMetaData();
       long stopTime=System.currentTimeMillis();
       //increase one usagecount
       dbConn.increaseUsageCount(1);
@@ -446,7 +385,7 @@
     {
       MetaCatUtil.debugMessage("Couldn't find a DBConnection in the pool"
                                   +" which have same tag to the returned"
-                                  +" DBConnetion object");
+                                  +" DBConnetion object", 30);
       return;
                                   
     }//if
@@ -470,10 +409,17 @@
                           
         //set check out time to 0
         dbConn.setCheckOutTime(0);
-      
+        
         MetaCatUtil.debugMessage("Connection: "+dbConn.getTag()+" checked in.",
-                                                                        20);
+                                                                        35);
+         MetaCatUtil.debugMessage("Connection: "+dbConn.getTag()+"'s status: "
+                                                    +dbConn.getStatus(), 35);
+                                                                       
       }//if
+      else
+      {
+        MetaCatUtil.debugMessage("This DBConnection couldn't return", 30);
+      }//else
     }//else
    
  
@@ -489,6 +435,11 @@
   {
     int index = -1;
     String info = null;
+    //if conn is null return -1 too
+    if (conn==null)
+    {
+      return -1;
+    }
     //get tag of this returned DBConnection
     info = conn.getTag();
     //if the tag is null or empty, -1 will be returned
@@ -615,4 +566,56 @@
     }//while
   }//run
   
+  /**
+   * Method to get the number of free DBConnection in DBConnection pool
+   */
+  public int getFreeDBConnectionNumber()
+  {
+    int numberOfFreeDBConnetion = 0; //return number
+    DBConnection db = null; //single DBconnection
+    int poolSize = 0; //size of connection pool
+    //get the size of DBConnection pool
+    poolSize = connectionPool.size();
+    //Check every DBConnection in the pool
+    for ( int i=0; i<poolSize; i++)
+    {
+      
+      db = (DBConnection) connectionPool.elementAt(i);
+      //check the status of db. If it is free, count it
+      if (db.getStatus() == FREE)
+      {
+        numberOfFreeDBConnetion++;
+      }//if
+    }//for
+    //return the count result
+    return numberOfFreeDBConnetion;
+  }//getFreeDBConnectionNumber
+      
+   /**
+   * Method to print out the method name which have busy DBconnection
+   */
+  public void printMethodNameHavingBusyDBConnection()
+  {
+    
+    DBConnection db = null; //single DBconnection
+    int poolSize = 0; //size of connection pool
+    //get the size of DBConnection pool
+    poolSize = connectionPool.size();
+    //Check every DBConnection in the pool
+    for ( int i=0; i<poolSize; i++)
+    {
+      
+      db = (DBConnection) connectionPool.elementAt(i);
+      //check the status of db. If it is free, count it
+      if (db.getStatus() == BUSY)
+      {
+        MetaCatUtil.debugMessage("This method having a busy DBConnection: "
+                                    +db.getCheckOutMethodName(), 30);
+        MetaCatUtil.debugMessage("The busy DBConnection tag is: "
+                                    +db.getTag(), 30);
+      }//if
+    }//for
+  
+  }//printMethodNameHavingBusyDBConnection
+  
 }//DBConnectionPool
Index: src/edu/ucsb/nceas/metacat/DBConnection.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBConnection.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBConnection.java	(revision 1217)
@@ -379,5 +379,29 @@
     conn.commit();
   }//commit
   
+  /**
+   * Method to set commit mode
+   * @param autocommit, true of false to auto commit
+   */
+  public void setAutoCommit( boolean autoCommit) throws SQLException
+  {
+    conn.setAutoCommit(autoCommit);
+  }//setAutoCommit
   
+  /**
+   * Method to roll back
+   */
+  public void rollback() throws SQLException
+  {
+    conn.rollback();
+  }//rollback
+  
+  /**
+   * Method to get meta data
+   */
+  public DatabaseMetaData getMetaData() throws SQLException
+  {
+    return conn.getMetaData();
+  }//getMetaData
+  
 }//DBConnection class
Index: src/edu/ucsb/nceas/metacat/MetacatReplication.java
===================================================================
--- src/edu/ucsb/nceas/metacat/MetacatReplication.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/MetacatReplication.java	(revision 1217)
@@ -241,17 +241,21 @@
                                           HttpServletResponse response)
   {
     String subaction = ((String[])params.get("subaction"))[0];
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
 
     try {
-      conn = util.openDBConnection();
-      PreparedStatement pstmt = null;
-
+      //conn = util.openDBConnection();
+      dbConn=DBConnectionPool.
+               getDBConnection("MetacatReplication.handleServerControlRequest");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      
       // add server to server list
       if ( subaction.equals("add") ) {
         String replicate = ((String[])params.get("replicate"))[0];
         String server = ((String[])params.get("server"))[0];
-        pstmt = conn.prepareStatement("INSERT INTO xml_replication " +
+        pstmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
                                       "(server, last_checked, replicate) " +
                                       "VALUES ('" + server + "', to_date(" +
                                       "'01/01/00', 'MM/DD/YY'), '" +
@@ -258,13 +262,16 @@
                                       replicate + "')");
         pstmt.execute();
         pstmt.close();
-        conn.commit();
+        dbConn.commit();
         out.println("Server " + server + " added"); 
         response.setContentType("text/html");
         out.println("<html><body><table border=\"1\">");
         out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
         out.println("<b>replicate</b></td></tr>");
-        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
+        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
+        //increase dbconnection usage
+        dbConn.increaseUsageCount(1);
+        
         pstmt.execute();
         ResultSet rs = pstmt.getResultSet();
         boolean tablehasrows = rs.next();
@@ -284,17 +291,19 @@
       // delete server from server list
       } else if ( subaction.equals("delete") ) {
         String server = ((String[])params.get("server"))[0];
-        pstmt = conn.prepareStatement("DELETE FROM xml_replication " +
+        pstmt = dbConn.prepareStatement("DELETE FROM xml_replication " +
                                       "WHERE server LIKE '" + server + "'");
         pstmt.execute();
         pstmt.close();
-        conn.commit();
+        dbConn.commit();
         out.println("Server " + server + " deleted");
         response.setContentType("text/html");
         out.println("<html><body><table border=\"1\">");
         out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
         out.println("<b>replicate</b></td></tr>");
-        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
+        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
+        //increase dbconnection usage
+        dbConn.increaseUsageCount(1);
         pstmt.execute();
         ResultSet rs = pstmt.getResultSet();
         boolean tablehasrows = rs.next();
@@ -313,7 +322,7 @@
         out.println("<html><body><table border=\"1\">");
         out.println("<tr><td><b>server</b></td><td><b>last_checked</b></td><td>");
         out.println("<b>replicate</b></td></tr>");
-        pstmt = conn.prepareStatement("SELECT * FROM xml_replication");
+        pstmt = dbConn.prepareStatement("SELECT * FROM xml_replication");
         pstmt.execute();
         ResultSet rs = pstmt.getResultSet();
         boolean tablehasrows = rs.next();
@@ -326,7 +335,7 @@
         out.println("</table></body></html>");
       }
       pstmt.close();
-      conn.close();
+      //conn.close();
 
     } catch(Exception e) {
       System.out.println("Error in " + 
@@ -334,6 +343,24 @@
                          e.getMessage());
       e.printStackTrace(System.out);
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in " + 
+                "MetacatReplication.handleServerControlRequest to close pstmt "
+                 + ee.getMessage());
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+      
   }
   
   // download certificate with the public key from certURL and 
@@ -408,6 +435,8 @@
     String dbaction = "UPDATE"; // the default action is UPDATE
     boolean override = false;
     int serverCode = 1;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
    
     try {
       //if the url contains a dbaction then the default action is overridden
@@ -443,12 +472,16 @@
       String homeServer=(String)docinfoHash.get("home_server");
       util.debugMessage("homeServer: "+homeServer,20);
       // write the document here
-      Connection conn = util.openDBConnection();
-      DocumentImpl.writeReplication(conn, new StringReader(xmldoc), null, null,
-              dbaction, docid, user, null, homeServer, false);
+      //Connection conn = util.openDBConnection();
+      dbConn=DBConnectionPool.
+              getDBConnection("MetacatReplication.handleForceReplicateRequest");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      DocumentImpl.writeReplication(dbConn, 
+                  new StringReader(xmldoc), null, null, dbaction, docid, user, 
+                  null, homeServer, false);
               
        
-      conn.close();
+      //conn.close();
 
       MetacatReplication.replLog("document " + docid + " added to DB with " +
                                  "action " + dbaction);
@@ -458,6 +491,10 @@
                          "Request(): " + e.getMessage());
        e.printStackTrace();
     }
+    finally
+    {
+      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+    }//finally
   }
   
   /**
@@ -489,7 +526,7 @@
     boolean override = false;
     int serverCode = 1;
     String dbaction=null;
-    Connection conn=null;
+    //Connection conn=null;
     
     try 
     {
@@ -534,9 +571,9 @@
       //the xml_documents
       if (dbaction.equals("delete"))
       {
-        conn = util.getConnection();
-        DocumentImpl.delete(conn,docid,user,null);
-        util.returnConnection(conn);
+        //conn = util.getConnection();
+        DocumentImpl.delete(docid,user,null);
+        //util.returnConnection(conn);
       }
       //To data file insert or update is same
       else if (dbaction.equals("insert")||dbaction.equals("update"))
@@ -560,7 +597,7 @@
     } catch(Exception e) 
     {
       
-      util.returnConnection(conn);
+      //util.returnConnection(conn);
       util.debugMessage("ERROR in MetacatReplication.handleForceReplicate" +
                          "Request(): " + e.getMessage(), 30);
     }
@@ -575,14 +612,14 @@
   private void handleGetLockRequest(PrintWriter out, Hashtable params,
                                     HttpServletResponse response)
   {
-    Connection conn = null;
+    //Connection conn = null;
     try
     {
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "handleGetLockRequest");
+      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
+                                                "handleGetLockRequest");*/
       String docid = ((String[])params.get("docid"))[0];
       String remoteRev = ((String[])params.get("updaterev"))[0];
-      DocumentImpl requestDoc = new DocumentImpl(conn, docid);
+      DocumentImpl requestDoc = new DocumentImpl(docid);
       MetacatReplication.replLog("lock request for " + docid);
       int localRevInt = requestDoc.getRev();
       int remoteRevInt = Integer.parseInt(remoteRev);
@@ -612,7 +649,7 @@
         MetacatReplication.replLog("lock denied for " + docid + 
                                    "reason: client has outdated file");
       }
-      conn.close();
+      //conn.close();
     }
     catch(Exception e)
     {
@@ -634,12 +671,12 @@
   {
     String docid = ((String[])(params.get("docid")))[0];
     StringBuffer sb = new StringBuffer();
-    Connection conn = null;
+    //Connection conn = null;
     try
     {
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "handleGetDocumentInfoRequest");
-      DocumentImpl doc = new DocumentImpl(conn, docid);
+      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
+                                              "handleGetDocumentInfoRequest");*/
+      DocumentImpl doc = new DocumentImpl(docid);
       sb.append("<documentinfo><docid>").append(docid);
       sb.append("</docid><docname>").append(doc.getDocname());
       sb.append("</docname><doctype>").append(doc.getDoctype());
@@ -655,7 +692,7 @@
       sb.append("</rev></documentinfo>");
       response.setContentType("text/xml");
       out.println(sb.toString());
-      conn.close();
+      //conn.close();
     }
     catch (Exception e)
     {
@@ -792,7 +829,7 @@
   private void handleGetDocumentRequest(PrintWriter out, Hashtable params, 
                                         HttpServletResponse response)
   {
-    Connection conn = null;
+    //Connection dbConn = null;
     try
     {
       //try to open a https stream to test if the request server's public key
@@ -811,12 +848,12 @@
       }
       
       String docid = ((String[])(params.get("docid")))[0];
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "handleGetDocumentRequest");
-      DocumentImpl di = new DocumentImpl(conn, docid);
+      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
+                                                "handleGetDocumentRequest");*/
+      DocumentImpl di = new DocumentImpl(docid);
       response.setContentType("text/xml");
       out.print(di.toString());
-      conn.close();
+      //conn.close();
       MetacatReplication.replLog("document " + docid + " sent");
     
     }
@@ -849,7 +886,9 @@
   private void handleUpdateRequest(PrintWriter out, Hashtable params, 
                                     HttpServletResponse response)
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try
     {
       //try to open a https stream to test if the request server's public key
@@ -893,9 +932,12 @@
         delsql.append("and server_location = 1");
       }
      
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "handleUpdateRequest");
-      PreparedStatement pstmt = conn.prepareStatement(docsql.toString());
+      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
+                                                "handleUpdateRequest");*/
+      dbConn=DBConnectionPool.
+                  getDBConnection("MetacatReplication.handleUpdateRequest");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement(docsql.toString());
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
       boolean tablehasrows = rs.next();
@@ -975,7 +1017,10 @@
         }//while
       }//else
       
-      pstmt = conn.prepareStatement(delsql.toString());
+      pstmt = dbConn.prepareStatement(delsql.toString());
+      //usage count should increas 1
+      dbConn.increaseUsageCount(1);
+      
       pstmt.execute();
       rs = pstmt.getResultSet();
       tablehasrows = rs.next();
@@ -1002,7 +1047,7 @@
       doclist.append("</updates></replication>");
       MetaCatUtil.debugMessage("doclist: " + doclist.toString());
       pstmt.close();
-      conn.close();
+      //conn.close();
       response.setContentType("text/xml");
       out.println(doclist.toString());
      
@@ -1015,6 +1060,25 @@
       response.setContentType("text/xml");
       out.println("<error>e.getMessage()</error>");
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in MetacatReplication." +
+                "handleUpdaterequest to close pstmt: "+ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+        
+                        
+      
     
   }
   
@@ -1041,13 +1105,17 @@
                                                 HttpServletResponse response,
                                                 boolean printFlag)
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     PreparedStatement pstmt = null;
     try
     { 
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "handleGetCatalogRequest");
-      pstmt = conn.prepareStatement("select entry_type, " +
+      /*conn = MetacatReplication.getDBConnection("MetacatReplication." +
+                                                "handleGetCatalogRequest");*/
+      dbConn=DBConnectionPool.
+                 getDBConnection("MetacatReplication.handleGetCatalogRequest");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("select entry_type, " +
                               "source_doctype, target_doctype, public_id, " +
                               "system_id from xml_catalog");
       pstmt.execute();
@@ -1067,7 +1135,7 @@
         tablehasrows = rs.next();
       }
       sb.append("</xml_catalog>");
-      conn.close();
+      //conn.close();
       if(printFlag)
       {
         response.setContentType("text/xml");
@@ -1078,17 +1146,29 @@
     }
     catch(Exception e)
     {
-      try
-      {
-        pstmt.close();
-        conn.close();
-      }
-      catch(Exception ee)
-      {}
+      
       System.out.println("error in MetacatReplication.handleGetCatalogRequest:"+ 
                           e.getMessage());
       e.printStackTrace(System.out);
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.
+           debugMessage("Error in MetacatReplication.handleGetCatalogRequest: "
+           +ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+      
     return null;
   }
   
@@ -1145,15 +1225,18 @@
   public static String getServer(int serverCode)
   {
     //System.out.println("serverid: " + serverCode);
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try
     {
-      conn = MetacatReplication.getDBConnection("MetacatReplication." +
-                                                "getServer");
+      dbConn=DBConnectionPool.
+                  getDBConnection("MetacatReplication.getServer");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       String sql = new String("select server from " +
                               "xml_replication where serverid = " + 
                               serverCode);
-      PreparedStatement pstmt = conn.prepareStatement(sql);
+      pstmt = dbConn.prepareStatement(sql);
       //System.out.println("getserver sql: " + sql);
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -1163,8 +1246,8 @@
         //System.out.println("server: " + rs.getString(1));
         return rs.getString(1);
       }
-      pstmt.close();
-      conn.close();
+      
+      //conn.close();
     }
     catch(Exception e)
     {
@@ -1171,6 +1254,25 @@
       System.out.println("Error in MetacatReplication.getServer: " + 
                           e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in MetacactReplication.getserver: "+
+                                    ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//fianlly
+    }//finally
+        
+      
+        
     return null;
       //return null if the server does not exist
   }
@@ -1183,14 +1285,18 @@
    */
   public static int getServerCode(String server) throws Exception
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     PreparedStatement pstmt = null;
     int serverCode = 0;
 
     try {
 
-      conn = util.openDBConnection();
-      pstmt = conn.prepareStatement("SELECT serverid FROM xml_replication " +
+      //conn = util.openDBConnection();
+      dbConn=DBConnectionPool.
+                  getDBConnection("MetacatReplication.getServerCode");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("SELECT serverid FROM xml_replication " +
                                     "WHERE server LIKE '" + server + "'");
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -1198,7 +1304,7 @@
       if ( tablehasrows ) {  
         serverCode = rs.getInt(1);
         pstmt.close();
-        conn.close();
+        //conn.close();
         return serverCode;
       }
       
@@ -1206,11 +1312,22 @@
       throw e;
 
     } finally {
-      try {
+      try 
+      {
         pstmt.close();
-        conn.close();
-      } catch(Exception ee) {}
-    }
+        //conn.close();
+       }//try
+       catch(Exception ee) 
+       {
+         MetaCatUtil.debugMessage("Error in MetacatReplicatio.getServerCode: "
+                                  +ee.getMessage(), 30);
+                           
+       }//catch
+       finally
+       {
+         DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+       }//finally
+    }//finally
     
     return serverCode;
   }
@@ -1270,12 +1387,15 @@
    */
   public static boolean replToServer(String server)
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     PreparedStatement pstmt = null;
     try
     {
-      conn = MetacatReplication.getDBConnection("MetacatReplication.replToServer");
-      pstmt = conn.prepareStatement("select replicate from " + 
+      dbConn=DBConnectionPool.
+                  getDBConnection("MetacatReplication.repltoServer");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("select replicate from " + 
                                     "xml_replication where server like '" +
                                      server + "'");
       pstmt.execute();
@@ -1287,13 +1407,13 @@
         if(i == 1)
         {
           pstmt.close();
-          conn.close();
+          //conn.close();
           return true;
         }
         else
         {
           pstmt.close();
-          conn.close();
+          //conn.close();
           return false;
         }
       }
@@ -1308,59 +1428,21 @@
       try
       {
         pstmt.close();
-        conn.close();
-      }
+        //conn.close();
+      }//try
       catch(Exception ee)
-      {}
-    }
+      {
+        MetaCatUtil.debugMessage("Error in MetacatReplication.replToServer: "
+                                  +ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
     return false;
     //the default if this server does not exist is to not replicate to it.
   }
   
-  /**
-   * A method for redundantly trying to connect.  this method will attempt to 
-   * connect to the DB 3 times before failing.
-   * @param methodname the methodname from which this method is called.
-   */
-  public static Connection getDBConnection(String methodname) throws Exception
-  {
-    Connection conn = null;
-    try
-    {
-      try
-      { //this connection is prone to error for some reason so we 
-        //try to connect it three times before quiting.
-        conn = util.openDBConnection();
-        return conn;
-      }
-      catch(SQLException sqle)
-      {
-        try
-        {
-          conn = util.openDBConnection();
-          return conn;
-        }
-        catch(SQLException sqlee)
-        {
-          try
-          {
-            conn = util.openDBConnection();
-            return conn;
-          }
-          catch(SQLException sqleee)
-          {
-            System.out.println("error getting db connection in " + 
-                               methodname +  ": " +
-                               sqleee.getMessage());
-            return conn;
-          }
-        }
-      }
-    }
-    catch(Exception e)
-    {
-      throw new java.lang.Exception("error in " + methodname + ": " + 
-                          e.getMessage());
-    }
-  }
+  
 }
Index: src/edu/ucsb/nceas/metacat/DBQuery.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBQuery.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBQuery.java	(revision 1217)
@@ -59,7 +59,7 @@
   static final int WRITE = 2;
   static final int READ = 4;
  
-  private Connection  conn = null;
+  //private Connection  conn = null;
   private String  parserName = null;
   private MetaCatUtil util = new MetaCatUtil();
   /**
@@ -97,12 +97,12 @@
 
           // Open a connection to the database
           MetaCatUtil   util = new MetaCatUtil();
-          Connection dbconn = util.openDBConnection();
+          //Connection dbconn = util.openDBConnection();
 
           double connTime = System.currentTimeMillis();
 
           // Execute the query
-          DBQuery queryobj = new DBQuery(dbconn, util.getOption("saxparser"));
+          DBQuery queryobj = new DBQuery(util.getOption("saxparser"));
           FileReader xml = new FileReader(new File(xmlfile));
           Hashtable nodelist = null;
           nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
@@ -170,11 +170,11 @@
    * @param parserName the fully qualified name of a Java class implementing
    *                   the org.xml.sax.XMLReader interface
    */
-  public DBQuery( Connection conn, String parserName ) 
+  public DBQuery(String parserName ) 
                   throws IOException, 
                          SQLException, 
                          ClassNotFoundException {
-    this.conn = conn;
+    //this.conn = conn;
     this.parserName = parserName;
   }
   
@@ -211,17 +211,22 @@
       String fieldname = null;
       String fielddata = null;
       String relation = null;
-      Connection dbconn = null;
-      Connection dbconn2 = null;
+      //Connection dbconn = null;
+      //Connection dbconn2 = null;
       int rev = 0;
-      StringBuffer document = null; 
+      StringBuffer document = null;
+      DBConnection dbconn = null;
+      int serialNumber = -1;
       
       try {
-        if (conn == null || conn.isClosed()) {
+        /*if (conn == null || conn.isClosed()) {
           dbconn = util.openDBConnection();
         } else {
           dbconn = conn;
-        }
+        }*/
+        
+        dbconn=DBConnectionPool.getDBConnection("DBQuery.findDocuments");
+        serialNumber=dbconn.getCheckOutSerialNumber();
         // problem with ODBC driver multi-threading
      //   dbconn2 = util.openDBConnection(); // for use by AccessControlList
         
@@ -239,7 +244,7 @@
         while (tableHasRows) 
         {
           docid = rs.getString(1).trim();
-          if ( !hasPermission(dbconn, user, groups, docid) ) {
+          if ( !hasPermission(user, groups, docid) ) {
             // Advance to the next record in the cursor
             tableHasRows = rs.next();
             continue;
@@ -279,6 +284,8 @@
             
             PreparedStatement npstmt = dbconn.
                                        prepareStatement(btBuf.toString());
+            //should incease usage count
+            dbconn.increaseUsageCount(1);
             npstmt.execute();
             ResultSet btrs = npstmt.getResultSet();
             boolean hasBtRows = btrs.next();
@@ -293,7 +300,7 @@
                 // xmldoc = new DocumentImpl(dbconn, packageDocid);
                 //  thus use the following to get the doc info only
                 //  xmldoc = new DocumentImpl(dbconn);
-                xmldoc = new DocumentImpl(dbconn, packageDocid, false);
+                xmldoc = new DocumentImpl(packageDocid, false);
                 if (xmldoc == null) {
                   util.debugMessage("Document was null for: "+packageDocid, 50);
                 }
@@ -388,6 +395,8 @@
             //pstmt.close();
             pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
                                         doclist.toString()));
+            //increase dbconnection usage count
+            dbconn.increaseUsageCount(1);
             pstmt.execute();
             rs = pstmt.getResultSet();
             tableHasRows = rs.next();
@@ -394,7 +403,7 @@
             while(tableHasRows) 
             {
               docid = rs.getString(1).trim();
-              if ( !hasPermission(dbconn, user, groups, docid) ) {
+              if ( !hasPermission(user, groups, docid) ) {
                 // Advance to the next record in the cursor
                 tableHasRows = rs.next();
                 continue;
@@ -485,17 +494,22 @@
                            ee.getMessage());
         ee.printStackTrace(System.err);
       }
-      finally {
+      finally 
+      {
         try
         {
-          dbconn.close();
-        //  dbconn2.close();
-        }
-        catch(SQLException sqle)
+          pstmt.close();
+        }//try
+        catch (SQLException sqlE)
         {
-          System.out.println("error closing conn in DBQuery.findDocuments");
-        }
-      }
+          MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
+                                      +sqlE.getMessage(), 30);
+        }//catch
+        finally
+        {
+          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+        }//finally
+      }//finally
     //System.out.println("docListResult: ");
     //System.out.println(docListResult.toString());
     return docListResult;
@@ -507,11 +521,11 @@
    * in the order in which they appearred in the document.
    * @param nodename the name or path of the particular node.
    * @param docid the docid of the document you want the node from.
-   * @param conn a database connection-this allows this method to be static
    */
-  public static Object[] getNodeContent(String nodename, String docid, 
-                                        Connection conn)
+  public static Object[] getNodeContent(String nodename, String docid)
   {
+    DBConnection dbconn = null;
+    int serialNumber = -1;
     StringBuffer query = new StringBuffer();
     Vector result = new Vector();
     PreparedStatement pstmt = null;
@@ -521,7 +535,9 @@
     query.append("' and docid like '").append(docid).append("')");
     try
     {
-      pstmt = conn.prepareStatement(query.toString());
+      dbconn=DBConnectionPool.getDBConnection("DBQuery.getNodeContent");
+        serialNumber=dbconn.getCheckOutSerialNumber();
+      pstmt = dbconn.prepareStatement(query.toString());
 
       // Execute the SQL query using the JDBC connection
       pstmt.execute();
@@ -542,7 +558,13 @@
       {
         pstmt.close();
       }
-      catch(SQLException sqle) {}
+      catch(SQLException sqle) 
+      {}
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+      }
+      
     }
     return result.toArray();
   }
@@ -779,13 +801,14 @@
     * Check for "READ" permission on @docid for @user and/or @group 
     * from DB connection 
     */
-  private boolean hasPermission ( Connection conn, String user,
+  private boolean hasPermission (String user,
                                   String[] groups, String docid ) 
                   throws SQLException, Exception
   {
     // Check for READ permission on @docid for @user and/or @groups
-    AccessControlList aclobj = new AccessControlList(conn);
-    return aclobj.hasPermission("READ", user, groups, docid);
+    //AccessControlList aclobj = new AccessControlList();
+    //return aclobj.hasPermission("READ", user, groups, docid);
+    return AccessControlList.hasPermission("READ", user, groups, docid);
   }
 
   /**
@@ -794,8 +817,10 @@
     */
   private Vector getCurrentDocidListForDataPackage(String dataPackageDocid)
   {
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     Vector docIdList=new Vector();//return value
-    PreparedStatement pStmt;
+    PreparedStatement pStmt = null;
     ResultSet rs=null;
     String docIdInSubjectField=null;
     String docIdInObjectField=null;
@@ -803,7 +828,10 @@
     String query="SELECT subject, object from xml_relation where docId = ?";
     try
     {
-      pStmt=conn.prepareStatement(query);
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBQuery.getCurrentDocidListForDataPackage");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pStmt=dbConn.prepareStatement(query);
       //bind the value to query
       pStmt.setString(1, dataPackageDocid);
 
@@ -840,6 +868,22 @@
       util.debugMessage("Error in getDocidListForDataPackage: "
                             +e.getMessage(), 30);
     }//catch
+    finally
+    {
+      try
+      {
+        pStmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        util.debugMessage("Error in getDocidListForDataPackage: "
+                            +ee.getMessage(), 30);
+      }//catch     
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//fianlly
+    }//finally
     return docIdList;
   }//getCurrentDocidListForDataPackadge()
   
@@ -854,42 +898,36 @@
     Vector docIdList=new Vector();//return value
     Vector tripleList=null;
     String xml=null;
-    Connection dbConn=null;
+   
+      //initial a documentImpl object 
+      DocumentImpl packageDocument = 
+                  new DocumentImpl(dataPackageDocid);
+      //transfer to documentImpl object to string
+      xml=packageDocument.toString();
     
-    if (conn == null || conn.isClosed())
-    {
-      dbConn = util.openDBConnection();
-    }
-    else
-    {
-      dbConn=conn;
-    }
-    //initial a documentImpl object 
-    DocumentImpl packageDocument = new DocumentImpl(dbConn, dataPackageDocid);
-    //transfer to documentImpl object to string
-    xml=packageDocument.toString();
-    
-    //create a tripcollection object
-    TripleCollection tripleForPackage = new 
+      //create a tripcollection object
+      TripleCollection tripleForPackage = new 
                                      TripleCollection(new StringReader(xml));
-    //get the vetor of triples 
-    tripleList=tripleForPackage.getCollection();
+      //get the vetor of triples 
+      tripleList=tripleForPackage.getCollection();
     
-    for (int i= 0; i<tripleList.size(); i++)
-    {
-      //put subject docid  into docIdlist without duplicate
-      if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getSubject()))
+      for (int i= 0; i<tripleList.size(); i++)
       {
-        //put subject docid  into docIdlist
-         docIdList.add(((Triple)tripleList.get(i)).getSubject());
-      }
-      //put object docid into docIdlist without duplicate
-      if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getObject()))
-      {
-         docIdList.add(((Triple)(tripleList.get(i))).getObject());
-      }
-    }//for
+        //put subject docid  into docIdlist without duplicate
+        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getSubject()))
+        {
+          //put subject docid  into docIdlist
+          docIdList.add(((Triple)tripleList.get(i)).getSubject());
+        }
+        //put object docid into docIdlist without duplicate
+        if (!docIdList.contains(((Triple)tripleList.elementAt(i)).getObject()))
+        {
+          docIdList.add(((Triple)(tripleList.get(i))).getObject());
+        }
+      }//for
+  
     
+    
     return docIdList;
   }//getDocidListForPackageInXMLRevisions()  
   
@@ -904,12 +942,17 @@
   private boolean isDataPackageId(String docId)
   {
     boolean result=false;
-    PreparedStatement pStmt;
+    PreparedStatement pStmt = null;
     ResultSet rs=null;
     String query="SELECT docId from xml_relation where docId = ?";
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     try
     {
-      pStmt=conn.prepareStatement(query);
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBQuery.isDataPackageId");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pStmt=dbConn.prepareStatement(query);
       //bind the value to query
       pStmt.setString(1, docId);
       //execute the query
@@ -924,9 +967,25 @@
     }//try
     catch (SQLException e)
     {
-      util.debugMessage("Error in getDocidListForDataPackadge: "
+      util.debugMessage("Error in isDataPackageId: "
                             +e.getMessage(), 30);
     }
+    finally
+    {
+      try
+      {
+        pStmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in isDataPackageId: "
+                                                        + ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
     return result;
   }//isDataPackageId()
   
@@ -937,12 +996,12 @@
    * @param user, the name of user
    * @param groups, the user's group
    */ 
-   private boolean hasPermissionToExportPackage(Connection conn, String docId, 
+   private boolean hasPermissionToExportPackage(String docId, 
                                         String user, String[] groups)
                    throws Exception
    {
-     DocumentImpl doc=new DocumentImpl(conn,docId);
-     return doc.hasReadPermission(conn, user, groups,docId);
+     //DocumentImpl doc=new DocumentImpl(conn,docId);
+     return DocumentImpl.hasReadPermission(user, groups,docId);
    }
    
   /**
@@ -953,12 +1012,17 @@
   private int getCurrentRevFromXMLDoumentsTable(String docId)
   {
     int rev=-5;
-    PreparedStatement pStmt;
+    PreparedStatement pStmt = null;
     ResultSet rs=null;
     String query="SELECT rev from xml_documents where docId = ?";
+    DBConnection dbConn=null;
+    int serialNumber = -1;
     try
     {
-      pStmt=conn.prepareStatement(query);
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBQuery.getCurrentRevFromXMLDocumentsTable");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pStmt=dbConn.prepareStatement(query);
       //bind the value to query
       pStmt.setString(1, docId);
       //execute the query
@@ -977,9 +1041,25 @@
     }//try
     catch (SQLException e)
     {
-      util.debugMessage("Error in getDocidListForDataPackadge: "
+      util.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
                             +e.getMessage(), 30);
-    }
+    }//catch
+    finally
+    {
+      try
+      {
+        pStmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in getCurrentRevFromXMLDoumentsTable: "
+                                  +ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
     return rev;
   }//getCurrentRevFromXMLDoumentsTable
  
@@ -1018,11 +1098,11 @@
   private Vector getCurrentAllDocumentImpl( Vector docIdList)
                               throws McdbException,Exception
   {
-    Connection dbConn=null;
+    //Connection dbConn=null;
     Vector documentImplList=new Vector();
     int rev=0; 
     
-    if (conn == null || conn.isClosed())
+    /*if (conn == null || conn.isClosed())
     {
       dbConn = util.openDBConnection();
     }
@@ -1029,7 +1109,7 @@
     else
     {
       dbConn=conn;
-    }
+    }*/
     //for every docid in vector
     for (int i=0;i<docIdList.size();i++)
     {
@@ -1040,7 +1120,7 @@
                         +util.getOption("accNumSeparator")+rev;
       //create new documentImpl object
       DocumentImpl documentImplObject = 
-                                    new DocumentImpl(dbConn,docidPlusVersion);
+                                    new DocumentImpl(docidPlusVersion);
       //add them to vector                            
       documentImplList.add(documentImplObject);
       
@@ -1057,13 +1137,13 @@
   private Vector getOldVersionAllDocumentImpl( Vector docIdList)
                               throws McdbException,Exception
   {
-    Connection dbConn=null;
+    //Connection dbConn=null;
     Vector documentImplList=new Vector();
     String siteCode=null;
     String uniqueId=null;
     int rev=0; 
     
-    if (conn == null || conn.isClosed())
+    /*if (conn == null || conn.isClosed())
     {
       dbConn = util.openDBConnection();
     }
@@ -1070,7 +1150,7 @@
     else
     {
       dbConn=conn;
-    }
+    }*/
     //for every docid in vector
     for (int i=0;i<docIdList.size();i++)
     {
@@ -1078,7 +1158,7 @@
         String docidPlusVersion=(String)(docIdList.elementAt(i));
         //create new documentImpl object
         DocumentImpl documentImplObject = 
-                                    new DocumentImpl(dbConn,docidPlusVersion);
+                                    new DocumentImpl(docidPlusVersion);
         //add them to vector                            
         documentImplList.add(documentImplObject);
       
@@ -1141,10 +1221,10 @@
     byte[] byteString=null;
     InputStream source;
     DBTransform xmlToHtml;
-    Connection dbConn;
+    //Connection dbConn;
 
     //get the connection to the database
-    if (conn == null || conn.isClosed())
+    /*if (conn == null || conn.isClosed())
     {
       dbConn = util.openDBConnection();
     }
@@ -1151,10 +1231,10 @@
     else
     {
       dbConn=conn;
-    }
+    }*/
 
     //create a DBTransform ojbect
-    xmlToHtml = new DBTransform(dbConn);
+    xmlToHtml = new DBTransform();
     //head of html
     htmlDoc.append("<html><head></head><body>");
     for (int i=0; i<docImplList.size(); i++)
@@ -1197,7 +1277,7 @@
     zipOut.putNextEntry(zEntry);
     zipOut.write(byteString, 0, byteString.length);
     zipOut.closeEntry();
-    dbConn.close();
+    //dbConn.close();
         
   }//addHtmlSummaryToZipOutputStream
   
@@ -1218,7 +1298,7 @@
     ZipOutputStream zOut = null;
     String elementDocid=null;
     DocumentImpl docImpls=null;
-    Connection dbConn = null;
+    //Connection dbConn = null;
     Vector docIdList=new Vector();
     Vector documentImplList=new Vector();
     Vector htmlDocumentImplList=new Vector();
@@ -1231,7 +1311,7 @@
     version=MetaCatUtil.getVersionFromString(docIdString);
  
     //get the connection to the database
-    if (conn == null || conn.isClosed())
+    /*if (conn == null || conn.isClosed())
     {
       dbConn = util.openDBConnection();
     }
@@ -1238,7 +1318,7 @@
     else
     {
       dbConn=conn;
-    }
+    }*/
 
     //check if the reqused docId is a data package id
     if (!isDataPackageId(docId))//if it is not, throw a exception
@@ -1245,14 +1325,14 @@
     {
       Exception e = new Exception("The request the doc id " +docIdString+
                                     " is not a data package id");
-      dbConn.close();
+      //dbConn.close();
       throw e;
     }
-    else if(!hasPermissionToExportPackage(dbConn, docId, user, groups))
+    else if(!hasPermissionToExportPackage(docId, user, groups))
     {
       Exception e = new Exception("User " + user + " does not have permission"
                        +" to export the data package " + docIdString);
-      dbConn.close();
+      //dbConn.close();
       throw e;
     }
     else //it is a packadge id
@@ -1295,7 +1375,7 @@
         docImpls=(DocumentImpl)documentImplList.elementAt(i);
         
         //checking if the user has the permission to read the documents
-        if (docImpls.hasReadPermission(dbConn,user,groups,docImpls.getDocID()))
+        if (docImpls.hasReadPermission(user,groups,docImpls.getDocID()))
         { 
             //if the docImpls is metadata 
           if ((docImpls.getDoctype()).compareTo("BIN")!=0)  
@@ -1321,7 +1401,7 @@
       //add html summary file
       addHtmlSummaryToZipOutputStream(htmlDocumentImplList, zOut, rootName);
       zOut.finish(); //terminate the zip file
-      dbConn.close();
+      //dbConn.close();
       return zOut;
     }//else
   }//getZippedPackage()
Index: src/edu/ucsb/nceas/metacat/MetaCatUtil.java
===================================================================
--- src/edu/ucsb/nceas/metacat/MetaCatUtil.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/MetaCatUtil.java	(revision 1217)
@@ -50,7 +50,7 @@
   private static String propertiesFile = "edu.ucsb.nceas.metacat.metacat";
   private static boolean debug = false;
 
-  private Hashtable connectionPool = new Hashtable();
+  //private Hashtable connectionPool = new Hashtable();
 
   /** 
    * Determine our db adapter class and create an instance of that class
@@ -63,25 +63,8 @@
     }
   }
 
-// CONSTRUCTORS NOT NEEDED
-//  /**
-//   * Construct an instance of the utility class
-//   */
-//  public MetaCatUtil() {
-//
-//    options = (PropertyResourceBundle)
-//          PropertyResourceBundle.getBundle(propertiesFile);
-//  }
-//  
-//  /**
-//   * This constructor allows the usage of a different properties file
-//   * @param propFile the properties file that you wish to use.
-//   */
-//  public MetaCatUtil(String propFile)  {
-//
-//    propertiesFile = propFile;
-//  }
 
+
   /**
    * Instantiate a class using the name of the class at runtime
    *
@@ -132,152 +115,9 @@
     return value;
   }
 
-  /** 
-   * Utility method to establish a JDBC database connection using connection
-   * info from the properties file
-   */
-  public Connection openDBConnection()
-                throws SQLException, ClassNotFoundException {
-    return openDBConnection(getOption("dbDriver"), getOption("defaultDB"),
-                     getOption("user"), getOption("password"));
-  }
-
-  /** 
-   * Utility method to establish a JDBC database connection 
-   *
-   * @param dbDriver the string representing the database driver
-   * @param connection the string representing the database connectin parameters
-   * @param user name of the user to use for database connection
-   * @param password password for the user to use for database connection
-   */
-  public static Connection openDBConnection(String dbDriver, String connection,
-                String user, String password)
-                throws SQLException, ClassNotFoundException {
-
-     // Load the Oracle JDBC driver
-     Class.forName (dbDriver);
-
-     debugMessage("Opening connection: " + connection);
-     // Connect to the database
-     Connection conn = DriverManager.getConnection( connection, user, password);
-     return conn;
-  }
-
-  /* Utility method to create and return a pool of Connection objects */
-  public Hashtable getConnectionPool()
-                throws SQLException, ClassNotFoundException {
-
-    int initConn = (new Integer(getOption("initialConnections"))).intValue();
-    
-    for ( int i = 0; i < initConn; i++ ) {
-        connectionPool.put( openDBConnection(), Boolean.FALSE );
-    }    
-    
-    return connectionPool;
-  }
+ 
   
-  /* Utility method to get a unused Connection object from the pool */
-  public Connection getConnection()
-                throws SQLException, ClassNotFoundException, Exception 
-  {
-
-    Connection conn = null;
-    Enumeration connections = connectionPool.keys();
-    
-    synchronized (connectionPool) {
-      while (connections.hasMoreElements()) {
-
-        conn = (Connection)connections.nextElement();
-        Boolean b = (Boolean)connectionPool.get(conn);
-
-        if (conn == null || conn.isClosed()) {
-            // closed connection; replace it
-            conn = openDBConnection();
-            // update the pool to show this one taken
-            connectionPool.put(conn, Boolean.TRUE);  
-            
-            return conn;
-        } else if (b == Boolean.FALSE) {
-            // unused connection; test if it works and get it
-            try {
-                conn.setAutoCommit(true);
-            } catch (SQLException e) {
-                // problem with the connection, replace it
-                conn = openDBConnection();
-            }    
-            // update the pool to show this one taken
-            connectionPool.put(conn, Boolean.TRUE);    
-
-            return conn;
-        }    
-      }  
-    }   
-    
-    // If we get here, there no free connections;
-    // we need to make more
-    int incConn = (new Integer(getOption("incrementConnections"))).intValue();
-    int maxConn = (new Integer(getOption("maximumConnections"))).intValue();
-    int k = connectionPool.size();
-    if ( k >= maxConn ) {
-        throw new Exception("The maximum of " + maxConn + 
-                            " open db connections is reached." +
-                            " New db connection to MetaCat" +
-                            " cannot be established.");
-    }    
-
-    // decide how many new connections to open; no more than the maximum
-    if ( incConn > maxConn - k ) { incConn = maxConn - k; }
-    
-    // get them
-    for ( int i = 0; i < incConn; i++ ) {
-        connectionPool.put( openDBConnection(), Boolean.FALSE );
-    }
-
-    // Recurse to get one of the new connections
-    return getConnection();
-  }
   
-  /* Utility method to give the connection back to the pool */
-  public void returnConnection (Connection returned) {
-    
-    Connection conn;
-    Enumeration connections = connectionPool.keys();
-    
-    try {
-      if ( (returned != null) && !(returned.isClosed()) ) {
-        while (connections.hasMoreElements()) {
-          conn = (Connection)connections.nextElement();
-          if ( conn == returned ) {
-            connectionPool.put( conn, Boolean.FALSE );
-            break;
-          }    
-        }    
-      }
-    } catch (SQLException e) {}    
-  }
-
-  /* Return the size of the pool */
-  public int getPoolSize() {
-    return connectionPool.size();
-  }
-  
-  /* Utility method to close all the connection from the pool */
-  public void closeConnections() {
-    
-    Connection conn;
-    Enumeration connections = connectionPool.keys();
-    
-    while (connections.hasMoreElements()) {
-        conn = (Connection)connections.nextElement();
-        try {
-            if ( (conn != null) && !(conn.isClosed()) ) {
-              conn.close();
-            }    
-        } catch (SQLException e) {}    
-    }
-  }
-  
-  
   /** Utility method to convert a file handle into a URL */
   public static URL fileToURL(File file)
   {
Index: src/edu/ucsb/nceas/metacat/AssociateAccessPolicy.java
===================================================================
--- src/edu/ucsb/nceas/metacat/AssociateAccessPolicy.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/AssociateAccessPolicy.java	(revision 1217)
@@ -62,7 +62,7 @@
 
  
  
-  private Connection  conn = null;
+  private DBConnection  conn = null;
   private Vector docIdInAccessTable=null;
   private Vector docIdWithoutAccessEntry=null;
   private Vector notFoundDataSetId=null;
@@ -75,15 +75,17 @@
    */
   static public void main(String[] args) 
   {
-     Connection localConn=null;
-     MetaCatUtil localUtil=new MetaCatUtil();
+     DBConnection localConn=null;
+     int serialNumber = -1;
+     //MetaCatUtil localUtil=new MetaCatUtil();
      AssociateAccessPolicy policy=null;
      try
      {
-      localConn=localUtil.openDBConnection();
+      localConn=DBConnectionPool.getDBConnection("AssociateAccessPolict.main");
+      serialNumber=localConn.getCheckOutSerialNumber();
       policy = new AssociateAccessPolicy(localConn);
       policy.associateAccess();
-      localConn.close();   
+      //localConn.close();   
      }//try
      catch (Exception e) 
      {
@@ -90,7 +92,12 @@
         System.err.println("Error in AssociateAccessPolicy.main");
         System.err.println(e.getMessage());
         e.printStackTrace(System.err);
-     } 
+     }
+     finally
+     {
+       DBConnectionPool.returnDBConnection(localConn, serialNumber);
+     }//finally
+     
      if (!(policy.getNotFoundDataSetId()).isEmpty())
      {
          
@@ -126,7 +133,7 @@
    * @param parserName the fully qualified name of a Java class implementing
    *                   the org.xml.sax.XMLReader interface
    */
-  public AssociateAccessPolicy( Connection conn) 
+  public AssociateAccessPolicy( DBConnection conn) 
                   throws IOException, 
                          SQLException, Exception
   {   
@@ -166,15 +173,7 @@
     PreparedStatement pStmt;
     String docId;
     ResultSet rs=null;
-    Connection dbConn=null;
-    if (conn == null || conn.isClosed())
-    {
-      dbConn = util.openDBConnection();
-    }
-    else
-    {
-      dbConn=conn;
-    }
+    
     //the query stirng
     String query="SELECT docid from xml_access";
     try
@@ -221,16 +220,9 @@
                       throws SQLException, McdbException,Exception
   {
     PreparedStatement pStmt;
-    Connection dbConn=null;
+    
     String query=null;
-    if (conn == null || conn.isClosed())
-    {
-      dbConn = util.openDBConnection();
-    }
-    else
-    {
-      dbConn=conn;
-    }
+  
     //the query stirng
     //we let accessfileid blank becuause we couldn't know access file
     query="INSERT INTO xml_access " + 
@@ -262,15 +254,8 @@
     PreparedStatement pStmt=null;
     String docId;
     ResultSet rs=null;
-    Connection dbConn=null;
-    if (conn == null || conn.isClosed())
-    {
-      dbConn = util.openDBConnection();
-    }
-    else
-    {
-      dbConn=conn;
-    }
+
+   
     //the query stirng
     String query="SELECT docid from xml_documents";
     try
Index: src/edu/ucsb/nceas/metacat/DBTransform.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBTransform.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBTransform.java	(revision 1217)
@@ -73,7 +73,7 @@
  */
 public class DBTransform {
 
-  private Connection	conn = null;
+  //private Connection	conn = null;
   private MetaCatUtil   util = null;
   private String 	configDir = null;
   private String	defaultStyle = null;
@@ -85,12 +85,12 @@
    *
    * @param conn the database connection from which to lookup the public ids
    */
-  public DBTransform( Connection conn ) 
+  public DBTransform() 
                   throws IOException, 
                          SQLException, 
                          ClassNotFoundException
   {
-    this.conn = conn;
+    //this.conn = conn;
     util = new MetaCatUtil();
     configDir = util.getOption("config-dir");
     defaultStyle = util.getOption("default-style");
@@ -318,11 +318,16 @@
                 String targettype) {
 
     // Look up the System ID of a particular object
-    PreparedStatement pstmt;
+    PreparedStatement pstmt = null;
     String the_system_id = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     try {
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBTransform.getSystemId");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       pstmt =
-        conn.prepareStatement("SELECT system_id " +
+        dbConn.prepareStatement("SELECT system_id " +
                 "FROM xml_catalog " +
                 "WHERE entry_type = ? " +
                 "AND source_doctype = ? " +
@@ -363,6 +368,22 @@
       return ("Error getting id in DBTransform.getSystemId:: " + 
                e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException sqlE)
+      {
+        MetaCatUtil.debugMessage("Error in DBTransform.getSystemId: "
+                                   +sqlE.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
     return the_system_id;
   }
 
@@ -382,8 +403,8 @@
         try {
                     
           // Open a connection to the database
-          MetaCatUtil   util = new MetaCatUtil();
-          Connection dbconn = util.openDBConnection();
+          /*MetaCatUtil   util = new MetaCatUtil();
+          Connection dbconn = util.openDBConnection();*/
 
           // Create a test document
           StringBuffer testdoc = new StringBuffer();
@@ -393,7 +414,7 @@
           testdoc.append("<title>My test doc</title></eml-dataset>");
 
           // Transform the document to the new doctype
-          DBTransform dbt = new DBTransform(dbconn);
+          DBTransform dbt = new DBTransform();
           dbt.transformXMLDocument(testdoc.toString(), 
                                    "-//NCEAS//eml-dataset//EN", 
                                    "-//W3C//HTML//EN", 
Index: src/edu/ucsb/nceas/metacat/MetaCatServlet.java
===================================================================
--- src/edu/ucsb/nceas/metacat/MetaCatServlet.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/MetaCatServlet.java	(revision 1217)
@@ -105,7 +105,6 @@
 
   private ServletConfig config = null;
   private ServletContext context = null;
-  //private Hashtable connectionPool = new Hashtable();
   private String resultStyleURL = null;
   private String xmlcatalogfile = null;
   private String saxparser = null;
@@ -115,6 +114,7 @@
   private String htmlpath = null; 
   private PropertyResourceBundle options = null;
   private MetaCatUtil util = null;
+  private DBConnectionPool connPool = null;
 
   /**
    * Initialize the servlet by creating appropriate database connections
@@ -127,6 +127,9 @@
       System.out.println("MetaCatServlet Initialize");
 
       util = new MetaCatUtil();
+      
+      //initial DBConnection pool
+      connPool = DBConnectionPool.getInstance();
 
       // Get the configuration file information
       resultStyleURL = util.getOption("resultStyleURL");
@@ -137,16 +140,12 @@
       servletpath = util.getOption("servletpath");
       htmlpath = util.getOption("htmlpath");
 
-// MOVED IT TO doGet() & doPost()
-//      try {
-//        // Open a pool of db connections
-//        connectionPool = util.getConnectionPool();
-//      } catch (Exception e) {
-//        System.err.println("Error creating pool of database connections");
-//        System.err.println(e.getMessage());
-//      }
+
     } catch ( ServletException ex ) {
       throw ex;
+    } catch (SQLException e) {
+      MetaCatUtil.debugMessage("Error in MetacatServlet.init: "
+                                          +e.getMessage(), 20);
     }
   }
 
@@ -154,10 +153,8 @@
    * Close all db connections from the pool
    */
   public void destroy() {
-    
-    if (util != null) {
-        util.closeConnections();
-    }
+      // Close all db connection  
+      connPool.release();
   }
 
   /** Handle "GET" method requests from HTTP clients */
@@ -187,23 +184,13 @@
     if ( util == null ) {
         util = new MetaCatUtil(); 
     }
-    util.debugMessage("Connection pool size: "+util.getPoolSize(),1);
-    /*if ( connectionPool.isEmpty() ) {
-      try {
-       
-        connectionPool = util.getConnectionPool();
-      } catch (Exception e) {
-        System.err.println("Error creating pool of database connections in " +
-                            " MetaCatServlet.handleGetOrPost");
-        System.err.println(e.getMessage());
-      }
-    } */   
-    // Get a handle to the output stream back to the client
-    //PrintWriter pwout = response.getWriter();
-    //response.setContentType("text/html");
-
-    // Deal with forms that are encoded as "multipart/form-data" differently
-    // this is mainly used for uploading non-xml files using that may be binary
+    MetaCatUtil.debugMessage("Connection pool size: "
+                                     +connPool.getSizeOfDBConnectionPool(),10);
+    MetaCatUtil.debugMessage("Free DBConnection number: "
+                                     +connPool.getFreeDBConnectionNumber(), 10);
+    //Debug message to print out the method which have a busy DBConnection
+    connPool.printMethodNameHavingBusyDBConnection();
+   
     String ctype = request.getContentType();
     if (ctype != null && ctype.startsWith("multipart/form-data")) {
       handleMultipartForm(request, response);
@@ -215,7 +202,10 @@
       String[] docid = new String[3];
       Hashtable params = new Hashtable();
       Enumeration paramlist = request.getParameterNames();
+     
+    
       while (paramlist.hasMoreElements()) {
+      
         name = (String)paramlist.nextElement();
         value = request.getParameterValues(name);
   
@@ -232,10 +222,16 @@
         params.put(name,value); 
       }  
       
+    
+      //handle param is emptpy
+      if (params.isEmpty() || params == null)
+      {
+        return;
+      }
       //if the user clicked on the input images, decode which image
       //was clicked then set the action.
       String action = ((String[])params.get("action"))[0];  
-      util.debugMessage("Line 213: Action is: " + action, 1);
+      util.debugMessage("Line 230: Action is: " + action, 1);
   
       // This block handles session management for the servlet
       // by looking up the current session information for all actions
@@ -247,14 +243,16 @@
   
       // handle login action
       if (action.equals("login")) {
+        PrintWriter out = response.getWriter();
+        handleLoginAction(out, params, request, response);
+        out.close();
   
-        handleLoginAction(response.getWriter(), params, request, response);
-  
       // handle logout action  
       } else if (action.equals("logout")) {
+        PrintWriter out = response.getWriter();
+        handleLogoutAction(out, params, request, response);
+        out.close();
   
-        handleLogoutAction(response.getWriter(), params, request, response);
-  
       // aware of session expiration on every request  
       } else {   
   
@@ -280,13 +278,17 @@
        // Now that we know the session is valid, we can delegate the request
       // to a particular action handler
       if(action.equals("query")) {
-        handleQuery(response.getWriter(),params,response,username,groupnames);
+        PrintWriter out = response.getWriter();
+        handleQuery(out,params,response,username,groupnames);
+        out.close();
       } else if(action.equals("squery")) {
+        PrintWriter out = response.getWriter();
         if(params.containsKey("query")) {
-         handleSQuery(response.getWriter(),params,response,username,groupnames); 
+         handleSQuery(out, params,response,username,groupnames);
+         out.close();
         } else {
-          PrintWriter out = response.getWriter();
           out.println("Illegal action squery without \"query\" parameter");
+          out.close();
         }
       } else if (action.equals("export")) {
         
@@ -299,7 +301,8 @@
           handleInsertOrUpdateAction(out,params,response,username,groupnames);
         } else {  
           out.println("Permission denied for " + action);
-        }  
+        }
+        out.close();
       } else if (action.equals("delete")) {
         PrintWriter out = response.getWriter();
         if ( (username != null) &&  !username.equals("public") ) {
@@ -306,28 +309,36 @@
           handleDeleteAction(out, params, response, username, groupnames);
         } else {  
           out.println("Permission denied for " + action);
-        }  
+        }
+        out.close();
       } else if (action.equals("validate")) {
         PrintWriter out = response.getWriter();
-        handleValidateAction(out, params, response); 
+        handleValidateAction(out, params, response);
+        out.close();
       } else if (action.equals("getaccesscontrol")) {
         PrintWriter out = response.getWriter();
         handleGetAccessControlAction(out,params,response,username,groupnames);
+        out.close();
       } else if (action.equals("getprincipals")) {
         PrintWriter out = response.getWriter();
-        handleGetPrincipalsAction(out, username, password);  
+        handleGetPrincipalsAction(out, username, password);
+        out.close();
       } else if (action.equals("getdoctypes")) {
         PrintWriter out = response.getWriter();
-        handleGetDoctypesAction(out, params, response);  
+        handleGetDoctypesAction(out, params, response);
+        out.close();
       } else if (action.equals("getdtdschema")) {
         PrintWriter out = response.getWriter();
-        handleGetDTDSchemaAction(out, params, response);  
+        handleGetDTDSchemaAction(out, params, response);
+        out.close();
       } else if (action.equals("getdataguide")) {
         PrintWriter out = response.getWriter();
-        handleGetDataGuideAction(out, params, response);  
+        handleGetDataGuideAction(out, params, response);
+        out.close();
       } else if (action.equals("getlastdocid")) {
         PrintWriter out = response.getWriter();
-        handleGetMaxDocidAction(out, params, response);  
+        handleGetMaxDocidAction(out, params, response);
+        out.close();
       } else if (action.equals("login") || action.equals("logout")) {
       } else if (action.equals("protocoltest")) {
         String testURL = "metacat://dev.nceas.ucsb.edu/NCEAS.897766.9";
@@ -376,11 +387,12 @@
         out.println("<error>");
         out.println("Error: action not registered.  Please report this error.");
         out.println("</error>");
+        out.close();
       }
       
-      util.closeConnections();
+      //util.closeConnections();
       // Close the stream to the client
-      // out.close();
+      //out.close();
     }
   }
   
@@ -412,16 +424,18 @@
       response.setContentType("text/xml");
       out.println(sess.getMessage()); 
     } else {
-      Connection conn = null;
+     
       try {
-        conn = util.getConnection();
-        DBTransform trans = new DBTransform(conn);
+        
+        DBTransform trans = new DBTransform();
         response.setContentType("text/html");
         trans.transformXMLDocument(sess.getMessage(), "-//NCEAS//login//EN",
                                    "-//W3C//HTML//EN", qformat, out);
-        util.returnConnection(conn); 
+         
       } catch(Exception e) {
-        util.returnConnection(conn); 
+        
+        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLoginAction: "
+                                +e.getMessage(), 30);
       } 
       
     // any output is returned  
@@ -452,16 +466,18 @@
       response.setContentType("text/xml");
       out.println(output.toString()); 
     } else {
-      Connection conn = null;
+      
       try {
-        conn = util.getConnection();
-        DBTransform trans = new DBTransform(conn);
+       
+        DBTransform trans = new DBTransform();
         response.setContentType("text/html");
         trans.transformXMLDocument(output.toString(), "-//NCEAS//login//EN", 
                                    "-//W3C//HTML//EN", qformat, out);
-        util.returnConnection(conn); 
+         
       } catch(Exception e) {
-        util.returnConnection(conn); 
+        
+        MetaCatUtil.debugMessage("Error in MetaCatServlet.handleLogoutAction"
+                                  +e.getMessage(), 30);
       } 
     }
   }
@@ -566,19 +582,20 @@
   private Hashtable runQuery(String xmlquery, String user, String[] groups)
   {
     Hashtable doclist=null;
-    Connection conn = null;
+  
     try
     {
-      conn = util.getConnection();
-      DBQuery queryobj = new DBQuery(conn, saxparser);
+    
+      DBQuery queryobj = new DBQuery(saxparser);
       doclist = queryobj.findDocuments(new StringReader(xmlquery),user,groups);
-      util.returnConnection(conn);
+ 
       return doclist;
     } 
     catch (Exception e) 
     {
-      util.returnConnection(conn); 
-      util.debugMessage("Error in MetacatServlet.runQuery: " + e.getMessage());
+    
+      MetaCatUtil.debugMessage("Error in MetacatServlet.runQuery: " 
+                                                      + e.getMessage(), 30);
       doclist = null;
       return doclist;
     }    
@@ -597,18 +614,20 @@
                                     HttpServletResponse response,
                                     PrintWriter out, String qformat)
   {
-    Connection conn = null;
+  
     try {
-      conn = util.getConnection();
-      DBTransform trans = new DBTransform(conn);
+     
+      DBTransform trans = new DBTransform();
       response.setContentType("text/html");
       trans.transformXMLDocument(resultdoc, "-//NCEAS//resultset//EN", 
                                  "-//W3C//HTML//EN", qformat, out);
-      util.returnConnection(conn); 
+     
     }
     catch(Exception e)
     {
-      util.returnConnection(conn); 
+      
+      MetaCatUtil.debugMessage("Error in MetaCatServlet.transformResultset:"
+                                +e.getMessage(), 30);
     } 
   }
   
@@ -662,7 +681,7 @@
     ZipOutputStream zOut = null;
     DocumentImpl docImpls=null;
     DBQuery queryObj=null;
-    Connection conn = null;
+  
     String[] docs = new String[10];
     String docId = "";
 
@@ -673,9 +692,8 @@
         docs = (String[])params.get("docid");
       }
 
-      //get the connection to database
-      conn = util.getConnection();
-      queryObj = new DBQuery(conn, saxparser);//"saxparser" have to use though
+   
+      queryObj = new DBQuery(saxparser);//"saxparser" have to use though
                                               //it is not standard
       docId=docs[0];
       out = response.getOutputStream();
@@ -708,21 +726,18 @@
       }
       catch (IOException ioe)
       {
-        util.debugMessage("Problem with the servlet output " +
+        MetaCatUtil.debugMessage("Problem with the servlet output " +
                            "in MetacatServlet.handleReadAction: " +
-                           ioe.getMessage());
+                           ioe.getMessage(), 30);
         
 
       }
 
-      util.debugMessage("Error in MetacatServlet.handleReadAction: " +
-                         e.getMessage());
+      MetaCatUtil.debugMessage("Error in MetacatServlet.handleReadAction: " +
+                         e.getMessage(), 30);
       
     }//catch
-    finally 
-    {
-      util.returnConnection(conn);
-    }
+   
 
   }//handleExportAction
   
@@ -853,17 +868,18 @@
                throws ClassNotFoundException, IOException, SQLException, 
                       McdbException, Exception
   {
-    Connection conn = null;
+   
     try {
-      conn = util.getConnection();
-      DocumentImpl doc = new DocumentImpl(conn, docid);
+     
       
+      DocumentImpl doc = new DocumentImpl(docid);
+    
       //check the permission for read
-      if (!doc.hasReadPermission(conn, user, groups, docid))
+      if (!doc.hasReadPermission(user, groups, docid))
       {
         Exception e = new Exception("User " + user + " does not have permission"
                        +" to read the document with the docid " + docid);
-        util.returnConnection(conn);
+    
         throw e;
       }
      
@@ -915,6 +931,7 @@
       } else {
         // this is metadata doc
         if ( qformat.equals("xml") ) { 
+          
           // set content type first
           response.setContentType("text/xml");   //MIME type
           PrintWriter out = response.getWriter();
@@ -926,14 +943,15 @@
           // Look up the document type
           String doctype = doc.getDoctype();
           // Transform the document to the new doctype
-          DBTransform dbt = new DBTransform(conn);
+          DBTransform dbt = new DBTransform();
           dbt.transformXMLDocument(doc.toString(),
                                    doctype,"-//W3C//HTML//EN", qformat, out);
         }
       
       }
-    } finally {
-      util.returnConnection(conn);
+    } catch (Exception except) {
+      throw except;
+    
     }
     
   }
@@ -1017,17 +1035,17 @@
     } catch (MalformedURLException mue) {
       
       // this is metacat doc (data file or metadata doc)
-      Connection conn = null;
+  
       try {
-        conn = util.getConnection();
-        DocumentImpl doc = new DocumentImpl(conn, docid);
+       
+        DocumentImpl doc = new DocumentImpl(docid);
         
         //check the permission for read
-        if (!doc.hasReadPermission(conn, user, groups, docid))
+        if (!doc.hasReadPermission(user, groups, docid))
         {
           Exception e = new Exception("User " + user + " does not have "
                     +"permission to read the document with the docid " + docid);
-          util.returnConnection(conn);
+        
           throw e;
         } 
         
@@ -1063,8 +1081,9 @@
           zout.write(bytestring, 0, bytestring.length);
           zout.closeEntry();
         }
-      } finally {
-        util.returnConnection(conn);
+      } catch (Exception except) {
+        throw except;
+       
       }
       
     }
@@ -1077,14 +1096,13 @@
                throws ClassNotFoundException, IOException, SQLException,
                       McdbException, Exception
   {
-    Connection conn = null;
+  
+    PrintWriter out =null;
     try {
-      conn = util.getConnection();
-    
-      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid, conn);
-    
+   
       response.setContentType("text/html");  //MIME type
-      PrintWriter out = response.getWriter();
+      out = response.getWriter();
+      Object[] abstracts = DBQuery.getNodeContent(abstractpath, docid);
       out.println("<html><head><title>Abstract</title></head>");
       out.println("<body bgcolor=\"white\"><h1>Abstract</h1>");
       for (int i=0; i<abstracts.length; i++) {
@@ -1092,8 +1110,13 @@
       }
       out.println("</body></html>");
 
-    } finally {
-      util.returnConnection(conn);
+    } catch (Exception e) {
+       out.println("<?xml version=\"1.0\"?>");
+       out.println("<error>");
+       out.println(e.getMessage());
+       out.println("</error>");
+    
+   
     }
   }
   // END OF READ SECTION
@@ -1106,7 +1129,8 @@
   private void handleInsertOrUpdateAction(PrintWriter out, Hashtable params, 
                HttpServletResponse response, String user, String[] groups) {
 
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
 
     try {
       // Get the document indicated
@@ -1145,25 +1169,36 @@
         } else if (action[0].equals("update")) {
           doAction = "UPDATE";
         }
-
-        try {
+        
+        try 
+        {
           // get a connection from the pool
-          conn = util.getConnection();
-
+          dbConn=DBConnectionPool.
+                  getDBConnection("MetaCatServlet.handleInsertOrUpdateAction");
+          serialNumber=dbConn.getCheckOutSerialNumber();
+          
           // write the document to the database
-          try {
+          try 
+          {
             String accNumber = docid[0];
-            if (accNumber.equals("")) {
+            if (accNumber.equals("")) 
+            {
               accNumber = null;
-            }
-            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
+            }//if
+            newdocid = DocumentImpl.write(dbConn, xml, pub, dtd, doAction,
                                           accNumber, user, groups, validate);
-          } catch (NullPointerException npe) {
-            newdocid = DocumentImpl.write(conn, xml, pub, dtd, doAction,
+            
+          }//try 
+          catch (NullPointerException npe) 
+          {
+            newdocid = DocumentImpl.write(dbConn, xml, pub, dtd, doAction,
                                           null, user, groups, validate);
-          }
-        } finally {
-          util.returnConnection(conn);
+          }//catch
+        }//try 
+        finally 
+        {
+          // Return db connection
+          DBConnectionPool.returnDBConnection(dbConn, serialNumber);
         }    
 
         // set content type and other response header fields first
@@ -1272,17 +1307,15 @@
                HttpServletResponse response, String user, String[] groups) {
 
     String[] docid = (String[])params.get("docid");
-    Connection conn = null;
-
+  
     // delete the document from the database
     try {
-      // get a connection from the pool
-      conn = util.getConnection();
+ 
                                       // NOTE -- NEED TO TEST HERE
                                       // FOR EXISTENCE OF DOCID PARAM
                                       // BEFORE ACCESSING ARRAY
       try { 
-        DocumentImpl.delete(conn, docid[0], user, groups);
+        DocumentImpl.delete(docid[0], user, groups);
         response.setContentType("text/xml");
         out.println("<?xml version=\"1.0\"?>");
         out.println("<success>");
@@ -1302,9 +1335,7 @@
       out.println("<error>");
       out.println(e.getMessage()); 
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    } 
   }
   // END OF DELETE SECTION
   
@@ -1317,42 +1348,42 @@
 
     // Get the document indicated
     String valtext = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     
     try {
       valtext = ((String[])params.get("valtext"))[0];
     } catch (Exception nullpe) {
 
-      Connection conn = null;
+     
       String docid = null;
       try {
         // Find the document id number
         docid = ((String[])params.get("docid"))[0]; 
 
-        // get a connection from the pool
-        conn = util.getConnection();
-
+      
         // Get the document indicated from the db
-        DocumentImpl xmldoc = new DocumentImpl(conn, docid);
+        DocumentImpl xmldoc = new DocumentImpl(docid);
         valtext = xmldoc.toString();
 
       } catch (NullPointerException npe) {
         response.setContentType("text/xml");
         out.println("<error>Error getting document ID: " + docid + "</error>");
-        if ( conn != null ) { util.returnConnection(conn); }
+        //if ( conn != null ) { util.returnConnection(conn); }
         return;
       } catch (Exception e) {
         response.setContentType("text/html");
         out.println(e.getMessage()); 
-      } finally {
-        util.returnConnection(conn);
-      }  
+      } 
     }
 
-    Connection conn = null;
+  
     try {
       // get a connection from the pool
-      conn = util.getConnection();
-      DBValidate valobj = new DBValidate(saxparser,conn);
+      dbConn=DBConnectionPool.
+                  getDBConnection("MetaCatServlet.handleValidateAction");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      DBValidate valobj = new DBValidate(saxparser,dbConn);
       boolean valid = valobj.validateString(valtext);
 
       // set content type and other response header fields first
@@ -1367,7 +1398,8 @@
       response.setContentType("text/html");
       out.println(e.getMessage()); 
     } finally {
-      util.returnConnection(conn);
+      // Return db connection
+      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
     }  
   }
   // END OF VALIDATE SECTION
@@ -1382,14 +1414,17 @@
                                        HttpServletResponse response, 
                                        String username, String[] groupnames) {
 
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     String docid = ((String[])params.get("docid"))[0];
     
     try {
 
         // get connection from the pool
-        conn = util.getConnection();
-        AccessControlList aclobj = new AccessControlList(conn);
+        dbConn=DBConnectionPool.
+                 getDBConnection("MetaCatServlet.handleGetAccessControlAction");
+        serialNumber=dbConn.getCheckOutSerialNumber();
+        AccessControlList aclobj = new AccessControlList(dbConn);
         String acltext = aclobj.getACL(docid, username, groupnames);
         out.println(acltext);
 
@@ -1399,7 +1434,8 @@
       out.println(e.getMessage());
       out.println("</error>");
     } finally {
-      util.returnConnection(conn);
+      // Retrun db connection to pool
+      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
     }  
     
   }
@@ -1411,11 +1447,10 @@
   private void handleGetPrincipalsAction(PrintWriter out, String user,
                                          String password) {
 
-    Connection conn = null;
-
+   
     try {
 
-        // get connection from the pool
+        
         AuthSession auth = new AuthSession();
         String principals = auth.getPrincipals(user, password);
         out.println(principals);
@@ -1425,9 +1460,7 @@
       out.println("<error>");
       out.println(e.getMessage());
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    } 
     
   }
 
@@ -1438,13 +1471,11 @@
   private void handleGetDoctypesAction(PrintWriter out, Hashtable params, 
                                        HttpServletResponse response) {
 
-    Connection conn = null;
-    
+   
     try {
 
-        // get connection from the pool
-        conn = util.getConnection();
-        DBUtil dbutil = new DBUtil(conn);
+     
+        DBUtil dbutil = new DBUtil();
         String doctypes = dbutil.readDoctypes();
         out.println(doctypes);
 
@@ -1453,9 +1484,7 @@
       out.println("<error>");
       out.println(e.getMessage());
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    } 
     
   }
 
@@ -1466,7 +1495,7 @@
   private void handleGetDTDSchemaAction(PrintWriter out, Hashtable params,
                                         HttpServletResponse response) {
 
-    Connection conn = null;
+   
     String doctype = null;
     String[] doctypeArr = (String[])params.get("doctype");
 
@@ -1478,9 +1507,8 @@
 
     try {
 
-        // get connection from the pool
-        conn = util.getConnection();
-        DBUtil dbutil = new DBUtil(conn);
+       
+        DBUtil dbutil = new DBUtil();
         String dtdschema = dbutil.readDTDSchema(doctype);
         out.println(dtdschema);
 
@@ -1489,9 +1517,7 @@
       out.println("<error>");
       out.println(e.getMessage());
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    } 
     
   }
 
@@ -1502,7 +1528,7 @@
   private void handleGetDataGuideAction(PrintWriter out, Hashtable params, 
                                         HttpServletResponse response) {
 
-    Connection conn = null;
+  
     String doctype = null;
     String[] doctypeArr = (String[])params.get("doctype");
 
@@ -1514,9 +1540,8 @@
 
     try {
 
-        // get connection from the pool
-        conn = util.getConnection();
-        DBUtil dbutil = new DBUtil(conn);
+  
+        DBUtil dbutil = new DBUtil();
         String dataguide = dbutil.readDataGuide(doctype);
         out.println(dataguide);
 
@@ -1525,9 +1550,7 @@
       out.println("<error>");
       out.println(e.getMessage());
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    }
     
   }
 
@@ -1538,7 +1561,7 @@
   private void handleGetMaxDocidAction(PrintWriter out, Hashtable params, 
                                         HttpServletResponse response) {
 
-    Connection conn = null;
+
     String scope = ((String[])params.get("scope"))[0];
     if (scope == null) {
         scope = ((String[])params.get("username"))[0];
@@ -1546,9 +1569,8 @@
 
     try {
 
-        // get connection from the pool
-        conn = util.getConnection();
-        DBUtil dbutil = new DBUtil(conn);
+       
+        DBUtil dbutil = new DBUtil();
         String lastDocid = dbutil.getMaxDocid(scope);
         out.println("<?xml version=\"1.0\"?>");
         out.println("<lastDocid>");
@@ -1561,9 +1583,7 @@
       out.println("<error>");
       out.println(e.getMessage());
       out.println("</error>");
-    } finally {
-      util.returnConnection(conn);
-    }  
+    }
     
   }
 
@@ -1674,6 +1694,7 @@
       out.println("Error: action not registered.  Please report this error.");
       out.println("</error>");
     }
+    out.close();
   }
 
   /** 
@@ -1686,7 +1707,7 @@
                                   String username, String[] groupnames)
   {
     PrintWriter out = null;
-    Connection conn = null;
+    //Connection conn = null;
     String action = null;
     String docid = null;
   
@@ -1734,10 +1755,10 @@
                 // force replcation data file if metacat was configured
                 if (ReplicationHandler.getServerLocation(docid)==1)
                 {//local host document
-                  conn=util.getConnection();
+                  //conn=util.getConnection();
                   ForceReplicationHandler frh = new ForceReplicationHandler
-             (docid, "insert", false, ReplicationHandler.buildServerList(conn));
-                  conn.close();
+             (docid, "insert", false, ReplicationHandler.buildServerList());
+                  //conn.close();
                 }//if
                 else
                 {
@@ -1745,8 +1766,8 @@
                   if ((util.getOption("hub")).equals("super"))
                   {
                     ForceReplicationHandler frh = new ForceReplicationHandler
-                    (docid,true, ReplicationHandler.buildServerList(conn));
-                    conn.close();
+                    (docid,true, ReplicationHandler.buildServerList());
+                    //conn.close();
                   }//if
                   else
                   {
@@ -1773,15 +1794,7 @@
           out.println(e.getMessage()); 
           out.println("</error>");
         }
-        finally
-        {
-          try
-          {
-            conn.close();
-          }
-          catch (SQLException ee)
-          {}
-         }
+       
       }
       else 
       {
Index: src/edu/ucsb/nceas/metacat/DBSAXHandler.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBSAXHandler.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBSAXHandler.java	(revision 1217)
@@ -58,7 +58,7 @@
    private boolean 	stackCreated = false;
    private Stack 	  nodeStack;
    private Vector   nodeIndex;
-   private Connection	  conn = null;
+   private DBConnection	  connection = null;
    private DocumentImpl currentDocument;
    private DBSAXNode    rootNode;
    private String   action = null;
@@ -80,8 +80,8 @@
     *
     * @param conn the JDBC connection to which information is written
     */
-   public DBSAXHandler(Connection conn) {
-     this.conn = conn;
+   public DBSAXHandler(DBConnection conn) {
+     this.connection = conn;
      this.atFirstElement = true;
      this.processingDTD = false;
 
@@ -106,7 +106,7 @@
     *        resides.
     *
     */
-   public DBSAXHandler(Connection conn, String action, String docid, 
+   public DBSAXHandler(DBConnection conn, String action, String docid, 
                       String user, String[] groups, String pub, int serverCode)
    {
      this(conn);
@@ -133,7 +133,7 @@
     *        resides.
     *
     */
-   public DBSAXHandler(Connection conn, String action, String docid, 
+   public DBSAXHandler(DBConnection conn, String action, String docid, 
      String revision, String user, String[] groups, String pub, int serverCode)
    {
      this(conn);
@@ -152,7 +152,7 @@
      MetaCatUtil.debugMessage("start Document", 50);
 
      // Create the document node representation as root
-     rootNode = new DBSAXNode(conn, this.docid);
+     rootNode = new DBSAXNode(connection, this.docid);
      // Add the node to the stack, so that any text data can be 
      // added as it is encountered
      nodeStack.push(rootNode);
@@ -214,23 +214,43 @@
        rootNode.writeNodename(docname);
        try {
          // for validated XML Documents store a reference to XML DB Catalog
+         // Because this is select statement and it needn't to roll back if
+         // insert document action fialed.
+         // In order to decrease DBConnection usage count, we get a new 
+         // dbconnection from pool
          String catalogid = null;
+         DBConnection dbConn = null;
+         int serialNumber = -1;
+         
          if ( systemid != null ) {
-           Statement stmt = conn.createStatement();
-           ResultSet rs = stmt.executeQuery(
+           try
+           {
+            // Get dbconnection
+            dbConn=DBConnectionPool.getDBConnection
+                                          ("DBSAXHandler.startElement");
+            serialNumber=dbConn.getCheckOutSerialNumber();
+            
+            Statement stmt = dbConn.createStatement();
+            ResultSet rs = stmt.executeQuery(
                           "SELECT catalog_id FROM xml_catalog " +
                           "WHERE entry_type = 'DTD' " + 
                           "AND public_id = '" + doctype + "'");
-           boolean hasRow = rs.next();
-           if ( hasRow ) {
-            catalogid = rs.getString(1);
-           }
-           stmt.close();
+            boolean hasRow = rs.next();
+            if ( hasRow ) {
+              catalogid = rs.getString(1);
+            }
+            stmt.close();
+           }//try
+           finally
+           {
+             // Return dbconnection
+             DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+           }//finally
          }
          
          //create documentImpl object by the constructor which can specify
          //the revision
-         currentDocument = new DocumentImpl(conn, rootNode.getNodeID(), 
+         currentDocument = new DocumentImpl(connection, rootNode.getNodeID(), 
                                docname, doctype, docid, revision, action, user, 
                                this.pub, catalogid, this.serverCode);
          
@@ -242,7 +262,7 @@
      }      
 
      // Create the current node representation
-     currentNode = new DBSAXNode(conn, qName, localName, parentNode,
+     currentNode = new DBSAXNode(connection, qName, localName, parentNode,
                                  currentDocument.getRootNodeID(),docid,
                                  currentDocument.getDoctype());
                                
@@ -275,16 +295,18 @@
   public void run () {
     DBSAXNode currNode = null;
     DBSAXNode prevNode = null;
-    Connection dbconn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     String doctype = currentDocument.getDoctype();
     int step = 0;
     int counter = 0;
 
     try {
+      
       // Opening separate db connection for writing XML Index
-      MetaCatUtil util = new MetaCatUtil();
-      dbconn = util.openDBConnection();
-      dbconn.setAutoCommit(false);
+      dbConn=DBConnectionPool.getDBConnection("DBSAXHandler.run");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      dbConn.setAutoCommit(false);
       
       //the following while loop construct checks to make sure that the docid
       //of the document that we are trying to index is already
@@ -296,7 +318,9 @@
       {
         String xmlDocumentsCheck = "select distinct docid from xml_documents";
         PreparedStatement xmlDocCheck = 
-                                  dbconn.prepareStatement(xmlDocumentsCheck);
+                                 dbConn.prepareStatement(xmlDocumentsCheck);
+        // Increase usage count
+        dbConn.increaseUsageCount(1);
         xmlDocCheck.execute();
         ResultSet doccheckRS = xmlDocCheck.getResultSet();
         boolean tableHasRows = doccheckRS.next();
@@ -322,13 +346,14 @@
       Enumeration nodes = nodeIndex.elements();
       while ( nodes.hasMoreElements() ) {
         currNode = (DBSAXNode)nodes.nextElement();
-        currNode.updateNodeIndex(dbconn, docid, doctype);
+        currNode.updateNodeIndex(dbConn, docid, doctype);
       }
+      
     
-      dbconn.commit();
+      dbConn.commit();
          
       //if this is a package file
-      String packagedoctype = util.getOption("packagedoctype");
+      String packagedoctype = MetaCatUtil.getOption("packagedoctype");
       Vector packagedoctypes = new Vector();
       
       packagedoctypes = MetaCatUtil.getOptionList(packagedoctype);
@@ -336,36 +361,44 @@
       if ( packagedoctypes.contains(doctype) )
       {
         // write the package info to xml_relation table
-        RelationHandler rth = new RelationHandler(docid, dbconn);
+        RelationHandler rth = new RelationHandler(docid, dbConn);
         // from the relations get the access file id for that package
         String aclid = rth.getAccessFileID(docid);
         // if there are access file, write ACL for that package
         if ( aclid != null ) {
-          runAccessControlList(dbconn, aclid);
+          runAccessControlList(dbConn, aclid);
         }
+        
       }
+      
       // if it is an access file
       else if ( MetaCatUtil.getOptionList(
-                            util.getOption("accessdoctype")).contains(doctype) )
+                     MetaCatUtil.getOption("accessdoctype")).contains(doctype) )
       {
         // write ACL for the package
-        runAccessControlList(dbconn, docid);
+        runAccessControlList(dbConn, docid);
+        
       }
+     
       
-      dbconn.close();
+      //dbconn.close();
 
     } catch (Exception e) {
       try {
-        dbconn.rollback();
-        dbconn.close();
+        dbConn.rollback();
+        //dbconn.close();
       } catch (SQLException sqle) {}
       System.out.println("Error in DBSAXHandler.run " + e.getMessage());
       e.printStackTrace();
-    }      
+    }
+    finally
+    {
+      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+    }//finally      
   }
   
   // It runs in xmlIndex thread. It writes ACL for a package.
-  private void runAccessControlList (Connection conn, String aclid)
+  private void runAccessControlList (DBConnection conn, String aclid)
                                                 throws Exception
   {
     // read the access file from xml_nodes
Index: src/edu/ucsb/nceas/metacat/DocumentImpl.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DocumentImpl.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DocumentImpl.java	(revision 1217)
@@ -72,7 +72,7 @@
   static final int READ = 4;
   private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
 
-  private Connection conn = null;
+  private DBConnection connection = null;
   private String docid = null;
   private String updatedVersion=null;
   private String docname = null;
@@ -102,16 +102,16 @@
    * @param docid the identifier of the document to be created
    * @param readNodes flag indicating whether the xmlnodes should be read
    */
-  public DocumentImpl(Connection conn, String docid, boolean readNodes) 
+  public DocumentImpl(String docid, boolean readNodes) 
          throws McdbException 
   {
     try {
-      this.conn = conn;
+      //this.conn = conn;
       this.docid = docid;
       
       // Look up the document information
       getDocumentInfo(docid);
-
+      
       if (readNodes) {
         // Download all of the document nodes using a single SQL query
         // The sort order of the records is determined by the NodeComparator
@@ -118,6 +118,7 @@
         // class, and needs to represent a depth-first traversal for the
         // toXml() method to work properly
         nodeRecordList = getNodeRecordList(rootnodeid);
+        
       }
     
     } catch (McdbException ex) {
@@ -135,9 +136,9 @@
    * @param conn the database connection from which to read the document
    * @param docid the identifier of the document to be created
    */
-  public DocumentImpl(Connection conn, String docid) throws McdbException 
+  public DocumentImpl(String docid) throws McdbException 
   {
-    this(conn, docid, true);
+    this(docid, true);
   }
 
   /** 
@@ -164,7 +165,7 @@
    *        resides.
    *
    */
-  public DocumentImpl(Connection conn, long rootnodeid, String docname, 
+  /*public DocumentImpl(Connection conn, long rootnodeid, String docname, 
                       String doctype, String docid, String action, String user,
                       String pub, String catalogid, int serverCode)
                       throws SQLException, Exception
@@ -175,7 +176,7 @@
     this.doctype = doctype;
     this.docid = docid;
     writeDocumentToDB(action, user, pub, catalogid, serverCode);
-  }
+  }*/
   
   /** 
    * Construct a new document instance, writing the contents to the database.
@@ -206,13 +207,13 @@
    *        resides.
    *
    */
-  public DocumentImpl(Connection conn, long rootNodeId, String docName, 
+  public DocumentImpl(DBConnection conn, long rootNodeId, String docName, 
                       String docType, String docId, String newRevision, 
                       String action, String user,
                       String pub, String catalogId, int serverCode)
                       throws SQLException, Exception
   {
-    this.conn = conn;
+    this.connection = conn;
     this.rootnodeid = rootNodeId;
     this.docname = docName;
     this.doctype = docType;
@@ -228,14 +229,11 @@
                      String docname, String doctype, String accnum, String user)
                      throws SQLException, AccessionNumberException, Exception
   {
-    Connection dbConn = null;
-    MetaCatUtil ut = new MetaCatUtil();
+    
     try
     {
-      dbConn = ut.openDBConnection();
-      // get server location for this doc
-      int serverLocation=getServerLocationNumber(dbConn,accnum);
-      dbConn.close();
+       // get server location for this doc
+      int serverLocation=getServerLocationNumber(accnum);
       registerDocument(docname, doctype,accnum, user, serverLocation);
     }
     catch (Exception e)
@@ -242,15 +240,7 @@
     {
       throw e;
     }
-    finally
-    {
-      try
-      {
-        dbConn.close();
-      }
-      catch (Exception ee)
-      {}
-    }
+   
     
   }
   /**
@@ -280,20 +270,26 @@
                      String user, int serverCode)
                      throws SQLException, AccessionNumberException, Exception
   {
-    Connection dbconn = null;
-    MetaCatUtil util = new MetaCatUtil();
+    DBConnection dbconn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
+    //MetaCatUtil util = new MetaCatUtil();
     AccessionNumber ac;
     try {
-      dbconn = util.openDBConnection();
+      //dbconn = util.openDBConnection();
+      //check out DBConnection
+      dbconn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.registerDocument");
+      serialNumber=dbconn.getCheckOutSerialNumber();
       String docIdWithoutRev=MetaCatUtil.getDocIdFromString(accnum);
       int userSpecifyRev=MetaCatUtil.getVersionFromString(accnum);
-      int revInDataBase=getLatestRevisionNumber(dbconn, docIdWithoutRev);
+      int revInDataBase=getLatestRevisionNumber(docIdWithoutRev);
       //revIndataBase=-1, there is no record in xml_documents table
       //the data file is a new one, inert it into table
       //user specified rev should be great than 0
       if (revInDataBase==-1 && userSpecifyRev>0 )
       {
-        ac = new AccessionNumber(dbconn, accnum, "insert");
+        ac = new AccessionNumber(accnum, "insert");
       }
       //rev is greater the last revsion number and revInDataBase isn't -1
       // it is a updated data file
@@ -301,10 +297,10 @@
       {
         
         //archive the old entry 
-        archiveDocRevision(dbconn, docIdWithoutRev, user);
+        archiveDocRevision(docIdWithoutRev, user);
         //delete the old entry in xml_documents
-        deleteXMLDocuments(dbconn, docIdWithoutRev);
-        ac = new AccessionNumber(dbconn, accnum, "update");
+        deleteXMLDocuments(docIdWithoutRev);
+        ac = new AccessionNumber(accnum, "update");
       }
       //other situation
       else
@@ -336,21 +332,20 @@
       sql.append(sqlDateString).append(",");
       sql.append(sqlDateString).append(",");
       sql.append("'0')");
-      PreparedStatement pstmt = dbconn.prepareStatement(sql.toString());
+      pstmt = dbconn.prepareStatement(sql.toString());
       pstmt.execute();
       pstmt.close();
-      dbconn.close();
+      //dbconn.close();
     } 
     finally 
     {
       try
       {
-        dbconn.close();
+        pstmt.close();
       }
-      catch (SQLException sqlE)
+      finally
       {
-        util.debugMessage("Error in DocumentImpl.registerDocument:" +
-                                sqlE.getMessage(), 30);
+        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
       }
     }    
   }
@@ -385,14 +380,19 @@
                      String user, int serverCode)
                      throws SQLException, AccessionNumberException, Exception
   {
-    Connection dbconn = null;
-    MetaCatUtil util = new MetaCatUtil();
+    DBConnection dbconn = null;
+    int serialNumber = -1;
+    //MetaCatUtil util = new MetaCatUtil();
     AccessionNumber ac;
+    PreparedStatement pstmt = null;
     try {
-      dbconn = util.openDBConnection();
+      //dbconn = util.openDBConnection();
+       dbconn=DBConnectionPool.
+                  getDBConnection("DocumentImpl.registerDocumentInReplication");
+      serialNumber=dbconn.getCheckOutSerialNumber();
       String docIdWithoutRev=MetaCatUtil.getDocIdFromString(accnum);
       int userSpecifyRev=MetaCatUtil.getVersionFromString(accnum);
-      int revInDataBase=getLatestRevisionNumber(dbconn, docIdWithoutRev);
+      int revInDataBase=getLatestRevisionNumber(docIdWithoutRev);
       //revIndataBase=-1, there is no record in xml_documents table
       //the data file is a new one, inert it into table
       //user specified rev should be great than 0
@@ -399,7 +399,7 @@
       if (revInDataBase==-1 && userSpecifyRev>0 )
       {
        
-        ac = new AccessionNumber(dbconn, accnum, "insert");
+        ac = new AccessionNumber(accnum, "insert");
       }
       //rev is greater the last revsion number and revInDataBase isn't -1
       // it is a updated data file
@@ -407,10 +407,10 @@
       {
         
         //archive the old entry 
-        archiveDocRevision(dbconn, docIdWithoutRev, user);
+        archiveDocRevision(docIdWithoutRev, user);
         //delete the old entry in xml_documents
-        deleteXMLDocuments(dbconn, docIdWithoutRev);
-        ac = new AccessionNumber(dbconn, accnum, "update");
+        deleteXMLDocuments(docIdWithoutRev);
+        ac = new AccessionNumber(accnum, "update");
       }
       //other situation
       else
@@ -442,22 +442,15 @@
       sql.append(sqlDateString).append(",");
       sql.append(sqlDateString).append(",");
       sql.append("'0')");
-      PreparedStatement pstmt = dbconn.prepareStatement(sql.toString());
+      pstmt = dbconn.prepareStatement(sql.toString());
       pstmt.execute();
       pstmt.close();
-      dbconn.close();
+      //dbconn.close();
     } 
     finally 
     {
-      try
-      {
-        dbconn.close();
-      }
-      catch (SQLException sqlE)
-      {
-        util.debugMessage("Error in DocumentImpl.registerDocument:" +
-                                sqlE.getMessage());
-      }
+      pstmt.close();
+      DBConnectionPool.returnDBConnection(dbconn, serialNumber);
     }    
   }
   
@@ -539,23 +532,17 @@
   public static boolean getDataFileLockGrant(String accnum) 
                                                   throws Exception
   { 
-    Connection dbConn = null;
-    MetaCatUtil ut= new MetaCatUtil();
+    
     try
     {
-      dbConn = ut.openDBConnection();
-      int serverLocation=getServerLocationNumber(dbConn,accnum);
-      dbConn.close();
+      
+      int serverLocation=getServerLocationNumber(accnum);
+    
       return getDataFileLockGrant(accnum,serverLocation);
     }
     catch (Exception e)
     {
-      try
-      {
-        dbConn.close();
-      }
-      catch (Exception ee)
-      {}
+     
       throw e;
     }
   }
@@ -574,9 +561,9 @@
                                           throws Exception 
   {
     boolean flag=true;
-    MetaCatUtil util = new MetaCatUtil();
-    String docid = util.getDocIdFromString(accnum);
-    int rev = util.getVersionFromString(accnum);
+    //MetaCatUtil util = new MetaCatUtil();
+    String docid = MetaCatUtil.getDocIdFromString(accnum);
+    int rev = MetaCatUtil.getVersionFromString(accnum);
     
     if (serverCode == 1)
     {
@@ -594,8 +581,8 @@
       
       String server = MetacatReplication.getServer(serverCode);
       MetacatReplication.replLog("attempting to lock " + accnum);
-      URL u = new URL("https://" + server + "?server="
-           +util.getLocalReplicationServerName()+"&action=getlock&updaterev=" 
+      URL u = new URL("https://" + server + "?server=" +
+        MetaCatUtil.getLocalReplicationServerName()+"&action=getlock&updaterev=" 
            +rev + "&docid=" + docid);
       //System.out.println("sending message: " + u.toString());
       String serverResStr = MetacatReplication.getURLContent(u);
@@ -940,41 +927,54 @@
   private boolean isRevisionOnly(DocumentIdentifier docid) throws Exception
   {
     //System.out.println("inRevisionOnly");
-    PreparedStatement pstmt;
+    DBConnection dbconn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt =null;
     String rev = docid.getRev();
     String newid = docid.getIdentifier();
-    pstmt = conn.prepareStatement("select rev from xml_documents " +
+    try
+    {
+      dbconn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.isRevisionOnly");
+      serialNumber=dbconn.getCheckOutSerialNumber();
+      pstmt = dbconn.prepareStatement("select rev from xml_documents " +
                                   "where docid like '" + newid + "'");
-    pstmt.execute();
-    ResultSet rs = pstmt.getResultSet();
-    boolean tablehasrows = rs.next();
-    if(rev.equals("newest") || rev.equals("all"))
-    {
-      return false;
-    }
-    
-    if(tablehasrows)
-    {
-      int r = rs.getInt(1);
-      pstmt.close();
-      if(new Integer(rev).intValue() == r)
-      { //the current revision in in xml_documents
-        //System.out.println("returning false");
+      pstmt.execute();
+      ResultSet rs = pstmt.getResultSet();
+      boolean tablehasrows = rs.next();
+      if(rev.equals("newest") || rev.equals("all"))
+      {
         return false;
       }
-      else if(new Integer(rev).intValue() < r)
-      { //the current revision is in xml_revisions.
-        //System.out.println("returning true");
-        return true;
-      }
-      else if(new Integer(rev).intValue() > r)
-      { //error, rev cannot be greater than r
-        throw new Exception("requested revision cannot be greater than " +
+    
+      if(tablehasrows)
+      {
+        int r = rs.getInt(1);
+        pstmt.close();
+        if(new Integer(rev).intValue() == r)
+        { //the current revision in in xml_documents
+          //System.out.println("returning false");
+          return false;
+        }
+        else if(new Integer(rev).intValue() < r)
+        { //the current revision is in xml_revisions.
+          //System.out.println("returning true");
+          return true;
+        }
+        else if(new Integer(rev).intValue() > r)
+        { //error, rev cannot be greater than r
+          throw new Exception("requested revision cannot be greater than " +
                             "the latest revision number.");
+        }
       }
-    }
-    throw new Exception("the requested docid '" + docid.toString() + 
+      throw new Exception("the requested docid '" + docid.toString() + 
                         "' does not exist");
+    }//try
+    finally
+    {
+      pstmt.close();
+      DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+    }//finally
   }
 
   private void getDocumentInfo(String docid) throws McdbException, 
@@ -990,7 +990,9 @@
    */
   private void getDocumentInfo(DocumentIdentifier docid) throws McdbException 
   {
-    PreparedStatement pstmt;
+    DBConnection dbconn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     String table = "xml_documents";
         
     try
@@ -1013,7 +1015,10 @@
       
     }
     
-    try {
+    try 
+    {
+      dbconn=DBConnectionPool.getDBConnection("DocumentImpl.getDocumentInfo");
+      serialNumber=dbconn.getCheckOutSerialNumber();
       StringBuffer sql = new StringBuffer();
 // DOCTITLE attr cleared from the db
 //      sql.append("SELECT docname, doctype, rootnodeid, doctitle, ");
@@ -1025,7 +1030,7 @@
       sql.append("' and rev like '").append(docid.getRev()).append("'");
       //System.out.println(sql.toString());
       pstmt =
-        conn.prepareStatement(sql.toString());
+        dbconn.prepareStatement(sql.toString());
       // Bind the values to the query
       //pstmt.setString(1, docid.getIdentifier());
       //pstmt.setString(2, docid.getRev());
@@ -1051,10 +1056,10 @@
       
       //get doc  home server name
       
-      pstmt = conn.prepareStatement("select server " +
+      pstmt = dbconn.prepareStatement("select server " +
                         "from xml_replication where serverid = ?");
-                        
-      
+      //because connection use twise here, so we need to increase one
+      dbconn.increaseUsageCount(1);
       pstmt.setInt(1, serverlocation);
       pstmt.execute();
       rs = pstmt.getResultSet();
@@ -1078,9 +1083,11 @@
       pstmt.close();
       if (this.doctype != null) {
         pstmt =
-          conn.prepareStatement("SELECT system_id " +
+          dbconn.prepareStatement("SELECT system_id " +
                                   "FROM xml_catalog " +
                                  "WHERE public_id = ?");
+        //should increase usage count again
+        dbconn.increaseUsageCount(1);
         // Bind the values to the query
         pstmt.setString(1, doctype);
   
@@ -1099,6 +1106,22 @@
       throw new McdbException("Error accessing database connection in " +
                               "DocumentImpl.getDocumentInfo: ", e);
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("error in DocumentImple.getDocumentInfo: "
+                                    +ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+      }
+    }
 
     if (this.docname == null) {
       throw new McdbDocNotFoundException("Document not found: " + docid);
@@ -1110,9 +1133,11 @@
    *
    * @param rootnodeid the id of the root node of the node tree to look up
    */
-  private TreeSet getNodeRecordList(long rootnodeid) throws McdbException 
+  private TreeSet getNodeRecordList(long rootnodeid) throws McdbException
   {
-    PreparedStatement pstmt;
+    PreparedStatement pstmt = null;
+    DBConnection dbconn = null;
+    int serialNumber = -1;
     TreeSet nodeRecordList = new TreeSet(new NodeComparator());
     long nodeid = 0;
     long parentnodeid = 0;
@@ -1124,8 +1149,11 @@
     String quotechar = dbAdapter.getStringDelimiter();
 
     try {
+      dbconn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.getNodeRecordList");
+      serialNumber=dbconn.getCheckOutSerialNumber();
       pstmt =
-      conn.prepareStatement("SELECT nodeid,parentnodeid,nodeindex, " +
+      dbconn.prepareStatement("SELECT nodeid,parentnodeid,nodeindex, " +
            "nodetype,nodename,nodeprefix,nodedata " +               
            "FROM xml_nodes WHERE rootnodeid = ?");
 
@@ -1158,6 +1186,23 @@
       throw new McdbException("Error in DocumentImpl.getNodeRecordList " +
                               e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("error in DocumentImpl.getNodeRecordList: "
+                                    +ee.getMessage(), 30);
+      }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+      }
+    }
+      
 
     if (nodeRecordList != null) {
       return nodeRecordList;
@@ -1187,8 +1232,8 @@
       if (action.equals("INSERT")) {
         //AccessionNumber ac = new AccessionNumber();
         //this.docid = ac.generate(docid, "INSERT");
-        System.out.println("before pstmt");
-        pstmt = conn.prepareStatement(
+        
+        pstmt = connection.prepareStatement(
                 "INSERT INTO xml_documents " +
                 "(docid, rootnodeid, docname, doctype, " + 
                 "user_owner, user_updated, date_created, date_updated, " + 
@@ -1195,6 +1240,9 @@
                 "public_access, catalog_id, server_location, rev) " +
                 "VALUES (?, ?, ?, ?, ?, ?, " + sysdate + ", " + sysdate + 
                 ", ?, ?, ?, ?)");
+        // Increase dbconnection usage count
+        connection.increaseUsageCount(1);
+        
         //note that the server_location is set to 1. 
         //this means that "localhost" in the xml_replication table must
         //always be the first entry!!!!!
@@ -1221,8 +1269,8 @@
       } else if (action.equals("UPDATE")) {
 
         // Save the old document publicaccessentry in a backup table
-        DocumentImpl.archiveDocRevision( conn, docid, user );
-        DocumentImpl thisdoc = new DocumentImpl(conn, docid);
+        DocumentImpl.archiveDocRevision(connection, docid, user );
+        DocumentImpl thisdoc = new DocumentImpl(docid);
         int thisrev = thisdoc.getRev();
         
         //if the updated vesion is not greater than current one,
@@ -1240,18 +1288,23 @@
         
         // Delete index for the old version of docid
         // The new index is inserting on the next calls to DBSAXNode
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
                 "DELETE FROM xml_index WHERE docid='" + this.docid + "'");
+        // Increase dbconnection usage count
+        connection.increaseUsageCount(1);
+        
         pstmt.execute();
         pstmt.close();
 
         // Update the new document to reflect the new node tree
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
             "UPDATE xml_documents " +
             "SET rootnodeid = ?, docname = ?, doctype = ?, " +
             "user_updated = ?, date_updated = " + sysdate + ", " +
             "server_location = ?, rev = ?, public_access = ?, catalog_id = ? " +
             "WHERE docid = ?");
+        // Increase dbconnection usage count
+        connection.increaseUsageCount(1);
         // Bind the values to the query
         pstmt.setLong(1, rootnodeid);
         pstmt.setString(2, docname);
@@ -1276,7 +1329,7 @@
 
       // Do the insertion
       pstmt.execute();
-      System.out.println("after excecute");
+      
       pstmt.close();
 
     } catch (SQLException sqle) {
@@ -1298,7 +1351,7 @@
    * @param user the user that owns the document
    * @param groups the groups to which user belongs
    */
-  public static String write(Connection conn,String filename,
+  public static String write(DBConnection conn,String filename,
                              String pub, String dtdfilename,
                              String action, String docid, String user,
                              String[] groups )
@@ -1312,7 +1365,7 @@
                    pub, dtd, action, docid, user, groups, false);
   }
 
-  public static String write(Connection conn,Reader xml,String pub,Reader dtd,
+  public static String write(DBConnection conn,Reader xml,String pub,Reader dtd,
                              String action, String docid, String user,
                              String[] groups, boolean validate)
                 throws Exception {
@@ -1319,13 +1372,13 @@
     //this method will be called in handleUpdateOrInsert method 
     //in MetacatServlet class
     // get server location for this doc
-    int serverLocation=getServerLocationNumber(conn,docid);
+    int serverLocation=getServerLocationNumber(docid);
     //System.out.println("server location: "+serverLocation);
     return write(conn,xml,pub,dtd,action,docid,user,groups,serverLocation,false,
                  validate);
   }
 
-  public static String write(Connection conn, Reader xml, String pub,
+  public static String write(DBConnection conn, Reader xml, String pub,
                              String action, String docid, String user,
                              String[] groups )
                 throws Exception {
@@ -1332,7 +1385,7 @@
     if(action.equals("UPDATE"))
     {//if the document is being updated then use the servercode from the 
      //originally inserted document.
-      DocumentImpl doc = new DocumentImpl(conn, docid);
+      DocumentImpl doc = new DocumentImpl(docid);
       int servercode = doc.getServerlocation();
       return write(conn, xml, pub, action, docid, user, groups, servercode);
     }
@@ -1342,7 +1395,7 @@
     }
   }
   
-  public static String write( Connection conn, Reader xml,
+  public static String write(DBConnection conn, Reader xml,
                               String action, String docid, String user,
                               String[] groups, int serverCode )
                 throws Exception
@@ -1350,7 +1403,7 @@
     return write(conn,xml,null,action,docid,user,groups,serverCode);
   }
   
-  public static String write( Connection conn, Reader xml, String pub,
+  public static String write(DBConnection conn, Reader xml, String pub,
                               String action, String docid, String user,
                               String[] groups, int serverCode) 
                 throws Exception
@@ -1359,7 +1412,7 @@
                  serverCode,false,false);
   }
   
-  public static String write( Connection conn, Reader xml, String pub,
+  public static String write(DBConnection conn, Reader xml, String pub,
                               String action, String docid, String user,
                               String[] groups, int serverCode, boolean override)
                 throws Exception
@@ -1388,15 +1441,17 @@
    *        update will be locked and version checked.
    */
 
-  public static String write( Connection conn,Reader xml,String pub,Reader dtd,
-                              String action, String accnum, String user,
-                              String[] groups, int serverCode, boolean override,
-                              boolean validate)
+  public static String write(DBConnection conn, Reader xml,String pub,
+                         Reader dtd, String action, String accnum, String user,
+                         String[] groups, int serverCode, boolean override,
+                         boolean validate)
                 throws Exception
   {
     // NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV IN IT
-    MetaCatUtil util = new MetaCatUtil();
-    AccessionNumber ac = new AccessionNumber(conn, accnum, action);
+    //MetaCatUtil util = new MetaCatUtil();
+    MetaCatUtil.debugMessage("conn usage count before writting: "
+                                      +conn.getUsageCount(), 50);
+    AccessionNumber ac = new AccessionNumber(accnum, action);
     String docid = ac.getDocid();
     String rev = ac.getRev();
     MetaCatUtil.debugMessage("action: " + action + " servercode: " + 
@@ -1412,7 +1467,7 @@
       char istreamChar;
      
       // check for 'write' permission for 'user' to update this document
-      if ( !hasPermission(conn, user, groups, docid) ) {
+      if ( !hasPermission(user, groups, docid) ) {
         throw new Exception("User " + user + 
               " does not have permission to update XML Document #" + accnum);
       }        
@@ -1421,8 +1476,8 @@
       String updaterev = id.getRev();
       String server = MetacatReplication.getServer(serverCode);
       MetacatReplication.replLog("attempting to lock " + accnum);
-      URL u = new URL("https://" + server + "?server="
-           +util.getLocalReplicationServerName()+"&action=getlock&updaterev=" 
+      URL u = new URL("https://" + server + "?server="+
+        MetaCatUtil.getLocalReplicationServerName()+"&action=getlock&updaterev=" 
            +updaterev + "&docid=" + docid);
       //System.out.println("sending message: " + u.toString());
       String serverResStr = MetacatReplication.getURLContent(u);
@@ -1452,10 +1507,10 @@
         
         //If Metacat is super hub, tell all servers in its server list to get 
         //the new document, ture mean it is xml document
-        if ((util.getOption("hub")).equals("super"))
+        if ((MetaCatUtil.getOption("hub")).equals("super"))
         {
           ForceReplicationHandler frh = new ForceReplicationHandler(accnum, 
-                true, ReplicationHandler.buildServerList(conn));
+                true, ReplicationHandler.buildServerList());
         }
         else
         {
@@ -1495,7 +1550,7 @@
     if ( action.equals("UPDATE") ) {
       // check for 'write' permission for 'user' to update this document
 
-      if ( !hasPermission(conn, user, groups, docid) ) {
+      if ( !hasPermission(user, groups, docid) ) {
         throw new Exception("User " + user + 
               " does not have permission to update XML Document #" + accnum);
       }          
@@ -1506,6 +1561,7 @@
       
       XMLReader parser = initializeParser(conn, action, docid, rev, validate,
                                           user, groups, pub, serverCode, dtd);
+   
       conn.setAutoCommit(false);
       parser.parse(new InputSource(xml));
       conn.commit();
@@ -1525,10 +1581,11 @@
       //start the thread to replicate this new document out to the other servers
       //true mean it is xml document
       ForceReplicationHandler frh = new ForceReplicationHandler
-                (accnum, action, true,ReplicationHandler.buildServerList(conn));
+                (accnum, action, true,ReplicationHandler.buildServerList());
       
     }
-      
+    MetaCatUtil.debugMessage("Conn Usage count after writting: "
+                                                      +conn.getUsageCount(),50); 
     return(accnum);
   }
 
@@ -1547,22 +1604,19 @@
    * @param validate, if the xml document is valid or not
    */
 
-  public static String writeReplication( Connection conn,Reader xml,String pub,
-                Reader dtd, String action, String accnum, String user,
-                            String[] groups,String homeServer, boolean validate)
+  public static String writeReplication(DBConnection conn, Reader xml, 
+            String pub, Reader dtd, String action, String accnum, String user,
+            String[] groups,String homeServer, boolean validate)
                 throws Exception
   {
-    // NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV IN IT
-    MetaCatUtil util = new MetaCatUtil();
-    //AccessionNumber ac = new AccessionNumber(conn, accnum, action);
-    //String docid = ac.getDocid();
-    // String rev = ac.getRev();
-    String docid=util.getDocIdFromString(accnum);
-    String rev=(new Integer(util.getVersionFromString(accnum))).toString();
+   
+    String docid=MetaCatUtil.getDocIdFromString(accnum);
+    String rev=(new Integer(MetaCatUtil.getVersionFromString(accnum))).
+                                                                    toString();
     
     //check if xml_documents table has the document or not
     //if not, set action to insert
-    if (getLatestRevisionNumber(conn,docid)==-1)
+    if (getLatestRevisionNumber(docid)==-1)
     {
       action="INSERT";
     }
@@ -1581,70 +1635,8 @@
     MetaCatUtil.debugMessage("action: " + action + " servercode: " + 
                              serverCode, 10);
                         
-    /*if((serverCode != 1 && action.equals("UPDATE")) )
-    { 
-      int istreamInt; 
-      char istreamChar;
-      DocumentIdentifier id = new DocumentIdentifier(accnum);
-      String updaterev = id.getRev();
-      String server = MetacatReplication.getServer(serverCode);
-      MetacatReplication.replLog("attempting to lock " + accnum);
-      URL u = new URL("https://" + server + "?server="
-           +util.getLocalReplicationServerName()+"&action=getlock&updaterev=" 
-           +updaterev + "&docid=" + docid);
-     
-      String serverResStr = MetacatReplication.getURLContent(u);
-      String openingtag =serverResStr.substring(0, serverResStr.indexOf(">")+1);
-      if(openingtag.equals("<lockgranted>"))
-      {
-        try 
-        {
-          
-          MetacatReplication.replLog("lock granted for " + accnum + " from " +
-                                      server);
-          XMLReader parser = initializeParser(conn, action, docid, updaterev,
-                                  validate, user, groups, pub, serverCode, dtd);
-          conn.setAutoCommit(false);
-          parser.parse(new InputSource(xml)); 
-          conn.commit();
-          conn.setAutoCommit(true);
-        } 
-        catch (Exception e) 
-        {
-          conn.rollback();
-          conn.setAutoCommit(true);
-          throw e;
-        }
-        return (accnum);
-      }
+  
 
-      else if(openingtag.equals("<filelocked>"))
-      {
-        MetacatReplication.replLog("lock denied for " + accnum + " on " +
-                                   server + " reason: file already locked");
-        throw new Exception("The file specified is already locked by another " +
-                            "user.  Please wait 30 seconds, checkout the " +
-                            "newer document, merge your changes and try " +
-                            "again.");
-      }
-      else if(openingtag.equals("<outdatedfile>"))
-      {
-        MetacatReplication.replLog("lock denied for " + accnum + " on " +
-                                    server + " reason: local file outdated");
-        throw new Exception("The file you are trying to update is an outdated" +
-                            " version.  Please checkout the newest document, " +
-                            "merge your changes and try again.");
-      }
-    }*/
-    
-    /*if ( action.equals("UPDATE") ) {
-      
-      if ( !hasPermission(conn, user, groups, docid) ) {
-        throw new Exception("User " + user + 
-              " does not have permission to update XML Document #" + accnum);
-      }          
-    }*/
-
     try 
     { 
       
@@ -1672,7 +1664,7 @@
    *
    * @param docid the ID of the document to be deleted from the database
    */
-  public static void delete( Connection conn, String accnum,
+  public static void delete(String accnum,
                                  String user, String[] groups )
                 throws Exception 
   {
@@ -1685,34 +1677,82 @@
     // Determine if the docid,rev are OK for DELETE
     //AccessionNumber ac = new AccessionNumber(conn);
     //docid = ac.generate(docid, rev, "DELETE");
+    DBConnection conn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt =null;
+    try
+    {
+      //check out DBConnection
+      conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.delete");
+      serialNumber=conn.getCheckOutSerialNumber();
 
-    // NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV IN IT
-    AccessionNumber ac = new AccessionNumber(conn, accnum, "DELETE");
-    String docid = ac.getDocid();
-    String rev = ac.getRev();
+      // NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV IN IT
+      AccessionNumber ac = new AccessionNumber(accnum, "DELETE");
+      String docid = ac.getDocid();
+      String rev = ac.getRev();
     
 
     // check for 'write' permission for 'user' to delete this document
-    if ( !hasPermission(conn, user, groups, docid) ) {
-      throw new Exception("User " + user + 
+      if ( !hasPermission(user, groups, docid) ) {
+        throw new Exception("User " + user + 
               " does not have permission to delete XML Document #" + accnum);
-    }
+      }
 
-    conn.setAutoCommit(false);
-    // Copy the record to the xml_revisions table
-    DocumentImpl.archiveDocRevision( conn, docid, user );
+      conn.setAutoCommit(false);
+      // Copy the record to the xml_revisions table
+      DocumentImpl.archiveDocRevision(conn, docid, user );
 
-    // Now delete it from the xml_documents table
-    
-    Statement stmt = conn.createStatement();
-    stmt.execute("DELETE FROM xml_index WHERE docid = '" + docid + "'");
-    //stmt.execute("DELETE FROM xml_access WHERE docid = '" + docid + "'");
-    stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + docid + "'");
-    stmt.execute("DELETE FROM xml_relation WHERE docid = '" + docid + "'");
-    stmt.execute("DELETE FROM xml_documents WHERE docid = '" + docid + "'");
-    stmt.close();
-    conn.commit();
-    conn.setAutoCommit(true);
+      // Now delete it from the xml_index table
+      pstmt = conn.prepareStatement("DELETE FROM xml_index WHERE docid = ?");
+      pstmt.setString(1,docid);
+      pstmt.execute();
+      pstmt.close();
+      conn.increaseUsageCount(1);
+      
+      //stmt.execute("DELETE FROM xml_access WHERE docid = '" + docid + "'");
+      // Now delete it from xml_access table
+      pstmt = conn.
+              prepareStatement("DELETE FROM xml_access WHERE accessfileid = ?");
+      pstmt.setString(1, docid);
+      pstmt.execute();
+      pstmt.close();
+      conn.increaseUsageCount(1);
+      
+      // Delete it from relation table
+      pstmt = conn.
+               prepareStatement("DELETE FROM xml_relation WHERE docid = ?");
+      //increase usage count
+      conn.increaseUsageCount(1);
+      pstmt.setString(1, docid);
+      pstmt.execute();
+      pstmt.close();
+      
+      // Delete it from xml_doucments table
+      pstmt =conn.prepareStatement("DELETE FROM xml_documents WHERE docid = ?");
+      pstmt.setString(1, docid);
+      pstmt.execute();
+      pstmt.close();
+      //Usaga count increase 1
+      conn.increaseUsageCount(1);
+      
+      conn.commit();
+      conn.setAutoCommit(true);
+    }//try
+    finally
+    {
+      
+      try
+      {
+        // close preparedStatement
+        pstmt.close();
+      }//try
+      finally
+      {
+        //check in DBonnection
+        DBConnectionPool.returnDBConnection(conn, serialNumber);
+      }//finally
+    }//finally
     //IF this is a package document:
     //delete all of the relations that this document created.
     //if the deleted document is a package document its relations should 
@@ -1724,13 +1764,14 @@
     * Check for "WRITE" permission on @docid for @user and/or @groups 
     * from DB connection 
     */
-  private static boolean hasPermission ( Connection conn, String user,
+  private static boolean hasPermission (String user,
                                   String[] groups, String docid ) 
                   throws SQLException, Exception
   {
     // Check for WRITE permission on @docid for @user and/or @groups
-    AccessControlList aclobj = new AccessControlList(conn);
-    return aclobj.hasPermission("WRITE", user, groups, docid);
+    //AccessControlList aclobj = new AccessControlList(dbconn);
+    return AccessControlList.hasPermission("WRITE", user, groups, docid);
+    //return aclobj.hasPermission("WRITE", user, groups, docid);
   }
 
   /** 
@@ -1740,19 +1781,20 @@
     *@group, user's group
     * 
     */
-  public boolean hasReadPermission ( Connection conn, String user,
+  public static boolean hasReadPermission (String user,
                                   String[] groups, String docId ) 
                   throws SQLException, Exception
   {
     // Check for READ permission on @docid for @user and/or @groups
-    AccessControlList aclObj = new AccessControlList(conn);
-    return aclObj.hasPermission("READ", user, groups, docId);
+    //AccessControlList aclObj = new AccessControlList(conn);
+    //return aclObj.hasPermission("READ", user, groups, docId);
+    return AccessControlList.hasPermission("READ", user, groups, docId);
   }  
 
   /**
    * Set up the parser handlers for writing the document to the database
    */
-  private static XMLReader initializeParser(Connection conn, String action,
+  private static XMLReader initializeParser(DBConnection dbconn, String action,
                                String docid, String rev, boolean validate, 
                                    String user, String[] groups, String pub, 
                                    int serverCode, Reader dtd) 
@@ -1759,16 +1801,23 @@
                            throws Exception 
   {
     XMLReader parser = null;
+    //DBConnection conn = null;
+    //int serialNumber = -1;
     //
     // Set up the SAX document handlers for parsing
     //
     try {
+       //check out DBConnection
+      /*conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.initializeParse");
+      serialNumber=conn.getCheckOutSerialNumber();*/
+      
       //create a DBSAXHandler object which has the revision specification
-      ContentHandler chandler = new DBSAXHandler(conn, action, docid, rev,
-                                                 user, groups, pub, serverCode);
-      EntityResolver eresolver= new DBEntityResolver(conn,
+      ContentHandler chandler = new DBSAXHandler(dbconn, action, 
+                                    docid, rev, user, groups, pub, serverCode);
+      EntityResolver eresolver= new DBEntityResolver(dbconn,
                                                  (DBSAXHandler)chandler, dtd);
-      DTDHandler dtdhandler   = new DBDTDHandler(conn);
+      DTDHandler dtdhandler   = new DBDTDHandler(dbconn);
 
       // Get an instance of the parser
       String parserName = MetaCatUtil.getOption("saxparser");
@@ -1795,21 +1844,99 @@
     } catch (Exception e) {
       throw e;
     }
+    //finally
+    //{
+      //DBConnectionPool.returnDBConnection(conn, serialNumber);
+    //}
 
     return parser;
   }
 
+  /**
+   * Save a document entry in the xml_revisions table 
+   * Connection use as a paramter is in order to rollback feature
+   */
+  private static void archiveDocRevision(DBConnection dbconn, String docid, 
+                                                    String user) 
+ {
+    String sysdate = dbAdapter.getDateTimeFunction();
+    //DBConnection conn = null;
+    //int serialNumber = -1;
+    PreparedStatement pstmt = null;
+    
+    // create a record in xml_revisions table 
+    // for that document as selected from xml_documents
+   
+   try
+   {
+     //check out DBConnection
+     /*conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.archiveDocRevision");
+     serialNumber=conn.getCheckOutSerialNumber();*/
+     pstmt = dbconn.prepareStatement(
+      "INSERT INTO xml_revisions " +
+        "(docid, rootnodeid, docname, doctype, " +
+        "user_owner, user_updated, date_created, date_updated, " +
+        "server_location, rev, public_access, catalog_id) " +
+      "SELECT ?, rootnodeid, docname, doctype, " + 
+        "user_owner, ?, " + sysdate + ", " + sysdate + ", "+
+        "server_location, rev, public_access, catalog_id " +
+      "FROM xml_documents " +
+      "WHERE docid = ?");
+      // Increase dbconnection usage count
+      dbconn.increaseUsageCount(1);
+      // Bind the values to the query and execute it
+      pstmt.setString(1, docid);
+      pstmt.setString(2, user);
+      pstmt.setString(3, docid);
+      pstmt.execute();
+      pstmt.close();
+   }//try
+   catch (SQLException e)
+   {
+     MetaCatUtil.debugMessage("Error in DocumentImpl.archiveDocRevision : "+
+                                e.getMessage(), 30);
+   }//catch
+   finally
+   {
+     try
+     {
+       pstmt.close();
+     }//try
+     catch (SQLException ee)
+     {
+       MetaCatUtil.debugMessage("Error in DocumnetImpl.archiveDocRevision: "+
+                                  ee.getMessage(), 50);
+     }//catch
+     //finally
+     //{
+       
+       //check in DBConnection
+       //DBConnectionPool.returnDBConnection(conn, serialNumber);
+     //}//finally
+   }//finnally
+                                  
+
+  }//achiveDocRevision
+  
   /** Save a document entry in the xml_revisions table */
-  private static void archiveDocRevision(Connection conn, String docid,
-                                         String user) 
+  private static void archiveDocRevision(String docid, String user) 
  {
     String sysdate = dbAdapter.getDateTimeFunction();
+    DBConnection conn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
+    
     // create a record in xml_revisions table 
     // for that document as selected from xml_documents
    
    try
    {
-     PreparedStatement pstmt = conn.prepareStatement(
+     //check out DBConnection
+     conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.archiveDocRevision");
+     serialNumber=conn.getCheckOutSerialNumber();
+     pstmt = conn.prepareStatement(
       "INSERT INTO xml_revisions " +
         "(docid, rootnodeid, docname, doctype, " +
         "user_owner, user_updated, date_created, date_updated, " +
@@ -1825,27 +1952,73 @@
       pstmt.setString(3, docid);
       pstmt.execute();
       pstmt.close();
-   }
+   }//try
    catch (SQLException e)
    {
-   }
-   
+     MetaCatUtil.debugMessage("Error in DocumentImpl.archiveDocRevision : "+
+                                e.getMessage(), 30);
+   }//catch
+   finally
+   {
+     try
+     {
+       pstmt.close();
+     }//try
+     catch (SQLException ee)
+     {
+       MetaCatUtil.debugMessage("Error in DocumnetImpl.archiveDocRevision: "+
+                                  ee.getMessage(), 50);
+     }//catch
+     finally
+     {
+       //check in DBConnection
+       DBConnectionPool.returnDBConnection(conn, serialNumber);
+     }//finally
+   }//finnally
+                                  
 
-  }
+  }//achiveDocRevision
   
   /**
     * delete a entry in xml_table for given docid
     * @param docId, the id of the document need to be delete
     */
-  private static void deleteXMLDocuments(Connection conn, String docId) 
+  private static void deleteXMLDocuments(String docId) 
                                          throws SQLException 
   {
-    //delete a record 
-    PreparedStatement pStmt = 
+    DBConnection conn = null;
+    int serialNumber = -1;
+    PreparedStatement pStmt = null;
+    try
+    {
+      //check out DBConnection
+      conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.deleteXMLDocuments");
+      serialNumber=conn.getCheckOutSerialNumber();
+      //delete a record 
+      pStmt = 
              conn.prepareStatement("DELETE FROM xml_documents WHERE docid = '" 
                                               + docId + "'");
     pStmt.execute();
-    pStmt.close();
+    }//try
+    finally
+    {
+      try
+      {
+        pStmt.close();
+      }//try
+      catch (SQLException e)
+      {
+        MetaCatUtil.debugMessage("error in DocumentImpl.deleteXMLDocuments: "+
+                                  e.getMessage(), 50);
+      }//catch
+      finally
+      {
+        //return back DBconnection
+        DBConnectionPool.returnDBConnection(conn, serialNumber);
+      }//finally
+    }//finally
+      
 
   }//deleteXMLDocuments
   
@@ -1855,28 +2028,54 @@
     * The return value is integer because we want compare it to there new one
     * @param docid <sitecode>.<uniqueid> part of Accession Number
     */
-  private static int getLatestRevisionNumber(Connection conn, String docId)
+  private static int getLatestRevisionNumber(String docId)
                                       throws SQLException
   {
     int rev = 1;
-    PreparedStatement pStmt;
+    PreparedStatement pStmt = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    
+    try
+    {
+      //check out DBConnection
+      dbConn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.getLatestRevisionNumber");
+      serialNumber=dbConn.getCheckOutSerialNumber();
      
-    pStmt = conn.prepareStatement
+      pStmt = dbConn.prepareStatement
               ("SELECT rev FROM xml_documents WHERE docid='" + docId + "'");
-    pStmt.execute();
+      pStmt.execute();
 
-    ResultSet rs = pStmt.getResultSet();
-    boolean hasRow = rs.next();
-    if (hasRow)
+      ResultSet rs = pStmt.getResultSet();
+      boolean hasRow = rs.next();
+      if (hasRow)
+      {
+        rev = rs.getInt(1);
+        pStmt.close();
+      }
+      else
+      {
+        rev=-1;
+        pStmt.close();
+      }
+    }//try
+    finally
     {
-      rev = rs.getInt(1);
-      pStmt.close();
-    }
-    else
-    {
-      rev=-1;
-      pStmt.close();
-    }
+      try
+      {
+        pStmt.close();
+      }
+      catch (Exception ee)
+      {
+        MetaCatUtil.debugMessage("Error in DocumentImpl."+
+                        "getLatestRevisionNumber: "+ee.getMessage(), 50);
+      }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }
+    }//finally  
       
     return rev;
   }//getLatestRevisionNumber
@@ -1886,33 +2085,59 @@
    * 
    * @param accum <sitecode>.<uniqueid>.<rev>
    */
-  private static int getServerLocationNumber(Connection conn, String accNum)
+  private static int getServerLocationNumber(String accNum)
                                             throws SQLException
   {
     //get rid of revNum part
     String docId=MetaCatUtil.getDocIdFromString(accNum);
-    PreparedStatement pStmt;
-    int serverLocation;
+    PreparedStatement pStmt = null;
+    int serverLocation = 1;
+    DBConnection conn = null;
+    int serialNumber = -1;
+    
+    try
+    {
+      //check out DBConnection
+      conn=DBConnectionPool.
+                    getDBConnection("DocumentImpl.getServerLocationNumber");
+      serialNumber=conn.getCheckOutSerialNumber();
      
-    pStmt = conn.prepareStatement
+      pStmt = conn.prepareStatement
       ("SELECT server_location FROM xml_documents WHERE docid='" + docId + "'");
-    pStmt.execute();
+      pStmt.execute();
 
-    ResultSet rs = pStmt.getResultSet();
-    boolean hasRow = rs.next();
-    //if there is entry in xml_documents, get the serverlocation
-    if (hasRow)
+      ResultSet rs = pStmt.getResultSet();
+      boolean hasRow = rs.next();
+      //if there is entry in xml_documents, get the serverlocation
+      if (hasRow)
+      {
+        serverLocation = rs.getInt(1);
+        pStmt.close();
+      }
+      else
+      {
+        //if htere is no entry in xml_documents, we consider it is new document
+        //the server location is local host and value is 1
+        serverLocation=1;
+        pStmt.close();
+      }
+    }//try
+    finally
     {
-      serverLocation = rs.getInt(1);
-      pStmt.close();
-    }
-    else
-    {
-      // if htere is no entry in xml_documents, we consider it is new document
-      // the server location is local host and value is 1
-      serverLocation=1;
-      pStmt.close();
-    }
+      try
+      {
+        pStmt.close();
+      }//try
+      catch (Exception ee)
+      {
+        MetaCatUtil.debugMessage("Error in DocumentImpl.getServerLocationNu(): "
+                                    +ee.getMessage(), 50);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(conn, serialNumber);
+      }//finally
+    }//finally
       
     return serverLocation;
   }
@@ -1926,12 +2151,13 @@
   {
     PreparedStatement pStmt=null;
     int serverLocation=-2;
-    Connection dbConn = null;
-    MetaCatUtil util = new MetaCatUtil();
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    //MetaCatUtil util = new MetaCatUtil();
     
     
     //we should consider about local host too
-    if (serverName.equals(util.getLocalReplicationServerName()))
+    if (serverName.equals(MetaCatUtil.getLocalReplicationServerName()))
     { 
       serverLocation=1;
       return serverLocation;
@@ -1941,7 +2167,10 @@
     try
     {
       //check xml_replication table
-      dbConn=util.openDBConnection();
+      //dbConn=util.openDBConnection();
+      //check out DBConnection
+      dbConn=DBConnectionPool.getDBConnection("DocumentImpl.getServerCode");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       pStmt = dbConn.prepareStatement
       ("SELECT serverid FROM xml_replication WHERE server='" + serverName +"'");
       pStmt.execute();
@@ -1963,7 +2192,7 @@
     }
     catch (Exception e)
     {
-      util.debugMessage("Error in DocumentImpl.getServerCode(): "
+      MetaCatUtil.debugMessage("Error in DocumentImpl.getServerCode(): "
                                     +e.getMessage(), 30);
     }
     finally
@@ -1970,10 +2199,17 @@
     {
       try
       {
-        dbConn.close();
+        pStmt.close();
       }
       catch (Exception ee)
-      {}
+      {
+        MetaCatUtil.debugMessage("Error in DocumentImpl.getServerCode(): "
+                                    +ee.getMessage(), 50);
+      }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }
     }
                  
       
@@ -1987,12 +2223,17 @@
   private static void  insertServerIntoReplicationTable(String server)
   {
     PreparedStatement pStmt=null;
-    Connection dbConn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     int replicate = 1;
-    MetaCatUtil util = new MetaCatUtil();
+    //MetaCatUtil util = new MetaCatUtil();
     try
     {
-       dbConn=util.openDBConnection();
+       //dbConn=util.openDBConnection();
+       //check out DBConnection
+       dbConn=DBConnectionPool.
+                getDBConnection("DocumentImpl.insertServIntoReplicationTable");
+       serialNumber=dbConn.getCheckOutSerialNumber();
        pStmt = dbConn.prepareStatement("INSERT INTO xml_replication " +
                                       "(server, last_checked, replicate) " +
                                       "VALUES ('" + server + "', to_date(" +
@@ -2001,22 +2242,30 @@
         pStmt.execute();
         pStmt.close();
         dbConn.commit();
-    }
+    }//try
     catch (Exception e)
     {
-      util.debugMessage("Error in DocumentImpl.getServerCode(): "
+      MetaCatUtil.debugMessage("Error in DocumentImpl.insertServerIntoRepli(): "
                                     +e.getMessage(), 30);
-    }
+    }//catch
     finally
     {
+     
       try
       {
         pStmt.close();
-        dbConn.close();
+      }//try
+      catch (Exception ee)
+      {
+        MetaCatUtil.debugMessage("Error in DocumentImpl.insetServerIntoRepl(): "
+                                    +ee.getMessage(), 50);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
       }
-      catch (Exception ee)
-      {}
-    }
+    
+    }//finally
 
   }
   
@@ -2031,7 +2280,8 @@
    * @param docid the id of the document to process
    */
   static public void main(String[] args) {
-     
+    DBConnection dbconn = null;
+    int serialNumber = -1;
     try {
       String filename    = null;
       String dtdfilename = null;
@@ -2103,12 +2353,14 @@
       
       // Open a connection to the database
       MetaCatUtil util = new MetaCatUtil();
-      Connection dbconn = util.openDBConnection();
+     
+      dbconn=DBConnectionPool.getDBConnection("DocumentImpl.main");
+      serialNumber=dbconn.getCheckOutSerialNumber();
 
       double connTime = System.currentTimeMillis();
       // Execute the action requested (READ, INSERT, UPDATE, DELETE)
       if (action.equals("READ")) {
-          DocumentImpl xmldoc = new DocumentImpl( dbconn, docid );
+          DocumentImpl xmldoc = new DocumentImpl(docid );
           if (useOldReadAlgorithm) {
             System.out.println(xmldoc.readUsingSlowAlgorithm());
           } else {
@@ -2115,7 +2367,7 @@
             xmldoc.toXml(new PrintWriter(System.out));
           }
       } else if (action.equals("DELETE")) {
-        DocumentImpl.delete(dbconn, docid, null, null);
+        DocumentImpl.delete(docid, null, null);
         System.out.println("Document deleted: " + docid);
       } else {
         String newdocid = DocumentImpl.write(dbconn, filename, null,
@@ -2156,5 +2408,10 @@
       System.err.println(e.getMessage());
       e.printStackTrace(System.err);
     }
+    finally
+    {
+      // Return db connection
+      DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+    }
   }
 }
Index: src/edu/ucsb/nceas/metacat/DBEntityResolver.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBEntityResolver.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBEntityResolver.java	(revision 1217)
@@ -52,7 +52,7 @@
  */
 public class DBEntityResolver implements EntityResolver
 {
-  private Connection conn = null;
+  private DBConnection connection = null;
   private DefaultHandler handler = null;
   private String docname = null;
   private String doctype = null;
@@ -64,9 +64,9 @@
    *
    * @param conn the JDBC connection to which information is written
    */
-  public DBEntityResolver(Connection conn)
+  public DBEntityResolver(DBConnection conn)
   {
-    this.conn = conn;
+    this.connection= conn;
   }
   /** 
    * Construct an instance of the DBEntityResolver class
@@ -75,9 +75,9 @@
    * @param handler the SAX handler to determine parsing context
    * @param dtd Reader of new dtd to be uploaded on server's file system
    */
-  public DBEntityResolver(Connection conn, DefaultHandler handler, Reader dtd)
+  public DBEntityResolver(DBConnection conn, DefaultHandler handler, Reader dtd)
   {
-    this.conn = conn;
+    this.connection = conn;
     this.handler = handler;
     this.dtdtext = dtd;
   }
@@ -185,8 +185,14 @@
                  throws SAXException
   {
     String systemid = null;
-    Statement stmt;
+    Statement stmt = null;
+    DBConnection conn = null;
+    int serialNumber = -1;
     try {
+      //check out DBConnection
+      conn=DBConnectionPool.getDBConnection("DBEntityResolver.getDTDSystemID");
+      serialNumber=conn.getCheckOutSerialNumber();
+      
       stmt = conn.createStatement();
       stmt.execute("SELECT system_id FROM xml_catalog " + 
                    "WHERE entry_type = 'DTD' AND public_id = '" +
@@ -201,6 +207,22 @@
       throw new SAXException
       ("DBEntityResolver.getDTDSystemID(): " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        stmt.close();
+      }//try
+      catch (SQLException sqlE)
+      {
+        MetaCatUtil.debugMessage("Error in DBEntityReolver.getDTDSystemId: "
+                                  +sqlE.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(conn, serialNumber);
+      }//finally
+    }//finally
 
     // return the selected System ID
     return systemid;
@@ -213,13 +235,22 @@
   private void registerDTD ( String doctype, String systemId )
                  throws SAXException
   {
+    //DBConnection conn = null;
+    //int serialNumber = -1;
+    PreparedStatement pstmt = null;
     // make a reference in db catalog table with @systemId for @doctype
     try {
-      PreparedStatement pstmt;
-      pstmt = conn.prepareStatement(
+      //check out DBConnection
+      //conn=DBConnectionPool.getDBConnection("DBEntityResolver.registerDTD");
+      //serialNumber=conn.getCheckOutSerialNumber();
+      
+      
+      pstmt = connection.prepareStatement(
              "INSERT INTO xml_catalog " +
              "(catalog_id, entry_type, public_id, system_id) " +
              "VALUES (null, 'DTD', ?, ?)");
+      // Increase usage count
+      connection.increaseUsageCount(1);
       // Bind the values to the query
       pstmt.setString(1, doctype);
       pstmt.setString(2, systemId);
@@ -230,6 +261,20 @@
       throw new SAXException
       ("DBEntityResolver.registerDTD(): " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException sqlE)
+      {
+        MetaCatUtil.debugMessage("Error in DBEntityReolver.registerDTD: "
+                                    +sqlE.getMessage(), 30);
+      }//catch
+      //DBConnectionPool.returnDBConnection(conn, serialNumber);
+    }//finally
+    
   }
 
   /** 
Index: src/edu/ucsb/nceas/metacat/ReplicationHandler.java
===================================================================
--- src/edu/ucsb/nceas/metacat/ReplicationHandler.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/ReplicationHandler.java	(revision 1217)
@@ -57,7 +57,7 @@
   int serverCheckCode = 1;
   MetaCatUtil util = new MetaCatUtil();
   Hashtable serverList = new Hashtable(); 
-  Connection conn;
+  //Connection conn;
   PrintWriter out;
   
   public ReplicationHandler(PrintWriter o)
@@ -82,13 +82,13 @@
     //xml_documents with an update_date > last_checked
     try
     {
-      try
-      { //this connection is prone to error for some reason so we 
+      //try
+      //{ //this connection is prone to error for some reason so we 
         //try to connect it three times before quiting.
-        conn = util.openDBConnection();
-      }
-      catch(SQLException sqle)
-      {
+        //conn = util.openDBConnection();
+      //}
+      //catch(SQLException sqle)
+      //{
         /*try
         {
           conn = util.openDBConnection();
@@ -101,13 +101,13 @@
           }
           catch(SQLException sqleee)
           {*/
-            System.out.println("error getting db connection in " + 
-                               "ReplicationHandler.run: " +
-                               sqle.getMessage());
+            //System.out.println("error getting db connection in " + 
+                               //"ReplicationHandler.run: " +
+                               //sqle.getMessage());
           //}
         //}
-      }
-      serverList = buildServerList(conn);
+      //}
+      serverList = buildServerList();
       //if serverList is null, metacat don't need to replication
       if (serverList==null||serverList.isEmpty())
       {
@@ -115,12 +115,13 @@
       }
       updateCatalog(serverList);
       update(serverList);
-      conn.close();
-    }
+      //conn.close();
+    }//try
     catch (Exception e)
     {
-      //System.out.println("Error in replicationHandler.run():"+e.getMessage());
-    }
+      MetaCatUtil.debugMessage("Error in replicationHandler.run():"
+                                                    +e.getMessage(), 30);
+    }//catch
   }
   
   /**
@@ -142,8 +143,9 @@
        should be kept anyway)
     */
     
-    Connection conn = null;
-    try
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    /*try
     {
       conn = util.getConnection();
     }
@@ -150,7 +152,7 @@
     catch (Exception e)
     {
       util.debugMessage("There is problem to get conncetion: "+e.getMessage());
-    }
+    }*/
     
     Enumeration keys;
     String server;
@@ -168,6 +170,9 @@
     
     try
     {
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.update");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       MetaCatUtil.debugMessage("init parser");
       parser = initParser(message);
       keys = serverList.keys();
@@ -235,7 +240,7 @@
           String docServer = (String)w.elementAt(2);
           
     
-          pstmt = conn.prepareStatement("select rev from xml_documents where "+
+         pstmt = dbConn.prepareStatement("select rev from xml_documents where "+
                                         "docid like '" + docid + "'");
           pstmt.execute();
           rs = pstmt.getResultSet();
@@ -292,7 +297,7 @@
             try
             {
              
-              String newDocid = DocumentImpl.writeReplication(conn, 
+              String newDocid = DocumentImpl.writeReplication(dbConn, 
                               new StringReader(newxmldoc),
                               (String)docinfoHash.get("public_access"),
                               null,  /* the dtd text */
@@ -302,6 +307,8 @@
                               null, /* null for groups[] */
                               docHomeServer, 
                               false /* validate */);
+              //increase usage
+              dbConn.increaseUsageCount(1);
               MetacatReplication.replLog("wrote doc " + docid + " from " + 
                                          docServer);
               /*System.out.println("wrote doc " + docid + " from " + 
@@ -379,7 +386,7 @@
         { //delete the deleted documents;
           Vector w = new Vector((Vector)d.elementAt(k));
           String docid = (String)w.elementAt(0);
-          if(!alreadyDeleted(docid, conn))
+          if(!alreadyDeleted(docid))
           {
           
             //because delete method docid should have rev number
@@ -386,7 +393,7 @@
             //so we just add one for it. This rev number is no sence.
             String accnum=docid+util.getOption("accNumSeparator")+"1";
             //System.out.println("accnum: "+accnum);
-            DocumentImpl.delete(conn, accnum, null, null);
+            DocumentImpl.delete(accnum, null, null);
             MetacatReplication.replLog("doc " + docid + " deleted");
           }
         }//for delete docs
@@ -409,9 +416,11 @@
             sql.append("server like '").append(server).append("'");
             //System.out.println("sql: " + sql.toString());
             pstmt.close();
-            pstmt = conn.prepareStatement(sql.toString());
+            pstmt = dbConn.prepareStatement(sql.toString());
+            //increase usage count
+            dbConn.increaseUsageCount(1);
             pstmt.executeUpdate();
-            //conn.commit();
+            dbConn.commit();
             System.out.println("last_checked updated to " + datestr + " on " +
                             server);
           }
@@ -429,9 +438,16 @@
       try
       {
         pstmt.close();
-        util.returnConnection(conn);
-      }
-      catch(Exception ee) {}
+      }//try
+      catch(Exception ee) 
+      {
+        MetaCatUtil.debugMessage("Error in ReplicationHandler.update to close"+
+                                " pstmt: "+ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
     }//finally
   }//update
   
@@ -440,12 +456,13 @@
    */
   private void updateCatalog(Hashtable serverList)
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try
     {
-      try
-      { //this connection is prone to error for some reason so we 
-        //try to connect it three times before quiting.
+      /*try
+      { 
         conn = util.openDBConnection();
       }
       catch(SQLException sqle)
@@ -467,7 +484,11 @@
                                sqleee.getMessage());
           }
         }
-      }
+      }*/
+      
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.updateCatalog");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       String server;
       Enumeration keys = serverList.keys();
       while(keys.hasMoreElements())
@@ -521,7 +542,9 @@
             sql.append("target_doctype, public_id, system_id) values (?,?,?,");
             sql.append("?,?)");
             //System.out.println("sql: " + sql.toString());
-            PreparedStatement pstmt = conn.prepareStatement(sql.toString());
+            pstmt = dbConn.prepareStatement(sql.toString());
+            //increase usage count 1
+            dbConn.increaseUsageCount(1);
             pstmt.setString(1, (String)v.elementAt(0));
             pstmt.setString(2, (String)v.elementAt(1));
             pstmt.setString(3, (String)v.elementAt(2));
@@ -532,7 +555,7 @@
           }
         }
       }
-      conn.close();
+      //conn.close();
     }
     catch(Exception e)
     {
@@ -539,14 +562,23 @@
       System.out.println("error in ReplicationHandler.updateCatalog: " + 
                           e.getMessage());
       e.printStackTrace(System.out);
+    }//catch
+    finally
+    {
       try
       {
-        conn.close();
-      }
-      catch (Exception ee)
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
       {
-      }
-    }
+        MetaCatUtil.debugMessage("Error in ReplicationHandler.updateCatalog "+
+                      "to close pstmt: "+ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finall
   }
   
   /**
@@ -560,10 +592,16 @@
    *   _             X             TRUE
    *   _             _             TRUE
    */
-  private static boolean alreadyDeleted(String docid, Connection conn)
+  private static boolean alreadyDeleted(String docid)
   {
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try
     {
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.alreadyDeleted");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       boolean xml_docs = false;
       boolean xml_revs = false;
       
@@ -570,7 +608,7 @@
       StringBuffer sb = new StringBuffer();
       sb.append("select docid from xml_revisions where docid like '");
       sb.append(docid).append("'");
-      PreparedStatement pstmt = conn.prepareStatement(sb.toString());
+      pstmt = dbConn.prepareStatement(sb.toString());
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
       boolean tablehasrows = rs.next();
@@ -583,7 +621,9 @@
       sb.append("select docid from xml_documents where docid like '");
       sb.append(docid).append("'");
       pstmt.close();
-      pstmt = conn.prepareStatement(sb.toString());
+      pstmt = dbConn.prepareStatement(sb.toString());
+      //increase usage count
+      dbConn.increaseUsageCount(1);
       pstmt.execute();
       rs = pstmt.getResultSet();
       tablehasrows = rs.next();
@@ -618,8 +658,20 @@
     }
     finally
     {
-      
-    }
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException ee)
+      {
+        MetaCatUtil.debugMessage("Error in replicationHandler.alreadyDeleted "+
+                          "to close pstmt: "+ee.getMessage(), 30);
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
     return false;
   }
   
@@ -629,14 +681,20 @@
    */
   private static String getAction(String docid)
   {
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try
     {
-      MetaCatUtil util = new MetaCatUtil();
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.getAction");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      //MetaCatUtil util = new MetaCatUtil();
       StringBuffer sql = new StringBuffer();
       sql.append("select docid from xml_documents where docid like '");
       sql.append(docid).append("'");
-      Connection conn = util.openDBConnection();
-      PreparedStatement pstmt = conn.prepareStatement(sql.toString());
+      //Connection conn = util.openDBConnection();
+      pstmt = dbConn.prepareStatement(sql.toString());
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
 
@@ -643,13 +701,13 @@
       if(rs.next())
       {
         pstmt.close();
-        conn.close();
+        //conn.close();
         return "UPDATE";
       }
       else
       {
         pstmt.close();
-        conn.close();
+        //conn.close();
         return "INSERT";
       }
     }
@@ -658,6 +716,22 @@
       System.out.println("error in replicationHandler.getAction: " + 
                           e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }
+      catch (SQLException sqlE)
+      {
+        MetaCatUtil.debugMessage("error in replicationHandler.getAction: " + 
+                     "to close pstmt: "+ sqlE.getMessage(), 30);
+      }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }
+    }//finally
     return "";
   }
   
@@ -666,13 +740,18 @@
    * and it's last update time.
    * @param conn a connection to the database
    */
-  public static Hashtable buildServerList(Connection conn)
+  public static Hashtable buildServerList()
   {
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     Hashtable sl = new Hashtable();
-    PreparedStatement pstmt;   
+    PreparedStatement pstmt = null;   
     try
     {
-      pstmt = conn.prepareStatement("select server, last_checked, replicate " +
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.buildServerList");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("select server, last_checked, replicate "+
                                     "from xml_replication");
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -697,6 +776,23 @@
       System.out.println("error in replicationHandler.buildServerList(): " +
                          e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      catch (SQLException sqlE)
+      {
+        MetaCatUtil.debugMessage("Error in ReplicationHandler.buildServerList: "
+                                +sqlE.getMessage());
+      }//catch
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+     
     return sl;
   }
    /**
@@ -706,16 +802,20 @@
   public static Hashtable getHomeServer(String docId)
   {
     Hashtable sl = new Hashtable();
-    Connection conn = null;
-    MetaCatUtil ut=new MetaCatUtil();
-    docId=ut.getDocIdFromString(docId);
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    //MetaCatUtil ut=new MetaCatUtil();
+    docId=MetaCatUtil.getDocIdFromString(docId);
     PreparedStatement pstmt=null;
     int serverLocation;
     try
     {
-      conn=ut.getConnection();
+      //get conection
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.getHomeServer");
+      serialNumber=dbConn.getCheckOutSerialNumber();
       //get a server location from xml_document table
-      pstmt = conn.prepareStatement("select server_location from xml_documents "
+      pstmt=dbConn.prepareStatement("select server_location from xml_documents "
                                             +"where docid = ?");
       pstmt.setString(1, docId);
       pstmt.execute();
@@ -729,11 +829,13 @@
       else
       {
         pstmt.close();
-        ut.returnConnection(conn);
+        //ut.returnConnection(conn);
         return null;
       }
-      pstmt = conn.prepareStatement("select server, last_checked, replicate " +
+      pstmt=dbConn.prepareStatement("select server, last_checked, replicate " +
                         "from xml_replication where serverid = ?");
+      //increase usage count
+      dbConn.increaseUsageCount(1);
       pstmt.setInt(1, serverLocation);
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -752,7 +854,7 @@
       else
       {
         pstmt.close();
-        ut.returnConnection(conn);
+        //ut.returnConnection(conn);
         return null;
       }
       pstmt.close();
@@ -759,7 +861,7 @@
     }
     catch(Exception e)
     {
-      System.out.println("error in replicationHandler.buildServerList(): " +
+      System.out.println("error in replicationHandler.getHomeServer(): " +
                          e.getMessage());
     }
     finally
@@ -767,13 +869,19 @@
       try
       {
         pstmt.close();
-        ut.returnConnection(conn);
+        //ut.returnConnection(conn);
       }
       catch (Exception ee)
       {
+        MetaCatUtil.debugMessage("Eror irn rplicationHandler.getHomeServer() "+
+                          "to close pstmt: "+ee.getMessage(), 30);
       }
-      
-    }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }
+    
+    }//finally
     return sl;
   }
   
@@ -784,17 +892,22 @@
    */
   public static int getServerLocation(String accNum) throws Exception
   {
-    Connection conn = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     PreparedStatement pstmt = null;
     int serverCode = 1;
-    MetaCatUtil ut = new MetaCatUtil();
-    String docId=ut.getDocIdFromString(accNum);
+    //MetaCatUtil ut = new MetaCatUtil();
+    String docId=MetaCatUtil.getDocIdFromString(accNum);
 
     try 
     {
 
-      conn = ut.openDBConnection();
-      pstmt = conn.prepareStatement("SELECT server_location FROM xml_documents " 
+      //conn = ut.openDBConnection();
+      //get conection
+      dbConn=DBConnectionPool.
+                  getDBConnection("ReplicationHandler.getServerLocation");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt=dbConn.prepareStatement("SELECT server_location FROM xml_documents " 
                               + "WHERE docid LIKE '" + docId + "'");
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -804,7 +917,7 @@
       {  
         serverCode = rs.getInt(1);
         pstmt.close();
-        conn.close();
+        //conn.close();
         return serverCode;
       }
       //if couldn't find in xml_documents table, we think server code is 1
@@ -812,7 +925,7 @@
       else
       {
         pstmt.close();
-        conn.close();
+        //conn.close();
         return serverCode;
       }
       
@@ -828,15 +941,20 @@
       try 
       {
         pstmt.close();
-        conn.close();
-        return serverCode;
+        //conn.close();
+        
       } 
       catch(Exception ee) 
       {
-        
+        MetaCatUtil.debugMessage("Erorr in Replication.getServerLocation "+
+                     "to close pstmt"+ee.getMessage(), 30);
       }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
     }//finally
-  
+   //return serverCode;
   }
   
   
Index: src/edu/ucsb/nceas/metacat/DBSAXNode.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBSAXNode.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBSAXNode.java	(revision 1217)
@@ -42,7 +42,7 @@
  */
 public class DBSAXNode extends BasicNode {
 
-  private Connection	conn;
+  private DBConnection	connection;
   private DBSAXNode	parentNode;
   private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
 
@@ -51,10 +51,10 @@
    *
    * @param conn the JDBC Connection to which all information is written
    */
-  public DBSAXNode (Connection conn, String docid) throws SAXException {
+  public DBSAXNode (DBConnection conn, String docid) throws SAXException {
 
     super();
-    this.conn = conn;
+    this.connection = conn;
     this.parentNode = null;
     writeChildNodeToDB("DOCUMENT", null, null, docid);
     updateRootNodeID(getNodeID());
@@ -67,13 +67,13 @@
    * @param tagname the name of the node
    * @param parentNode the parent node for this node being created
    */
-  public DBSAXNode (Connection conn, String qName, String lName,
+  public DBSAXNode (DBConnection conn, String qName, String lName,
                     DBSAXNode parentNode, long rootnodeid, 
                     String docid, String doctype) 
                                                throws SAXException {
 
     super(lName);
-    this.conn = conn;
+    this.connection = conn;
     this.parentNode = parentNode;
     setParentID(parentNode.getNodeID());
     setRootNodeID(rootnodeid);
@@ -89,7 +89,7 @@
                                  String data, String docid) 
                                  throws SAXException {
     try {
-      if(conn == null)
+      /*if(conn == null)
       {
         try
         {
@@ -101,21 +101,26 @@
           MetaCatUtil.debug("Error while getting db connection in " +
                             "DBSAXNode: " + e.getMessage());
         }
-      }
+      }*/
         
       PreparedStatement pstmt;
       if (nodetype == "DOCUMENT") {
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
             "INSERT INTO xml_nodes " +
             "(nodetype, nodename, nodeprefix, docid) " +
             "VALUES (?, ?, ?, ?)");
+        
+        // Increase DBConnection usage count
+        connection.increaseUsageCount(1);
         MetaCatUtil.debugMessage("INSERTING DOCNAME: " + nodename);
       } else {
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
             "INSERT INTO xml_nodes " +
             "(nodetype, nodename, nodeprefix, docid, " +
             "rootnodeid, parentnodeid, nodedata, nodeindex) " +
             "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
+        // Increase DBConnection usage count
+        connection.increaseUsageCount(1);
       }
 
       // Bind the values to the query
@@ -150,7 +155,10 @@
       pstmt.close();
 
       // get the generated unique id afterward
-      long nid = dbAdapter.getUniqueID(conn, "xml_nodes");
+      long nid = dbAdapter.
+                         getUniqueID(connection.getConnections(), "xml_nodes");
+      //should incease connection usage!!!!!!
+     
       
       if (nodetype.equals("DOCUMENT")) {
         // Record the root node id that was generated from the database
@@ -184,9 +192,11 @@
   public void updateRootNodeID(long nodeid) throws SAXException {
       try {
         PreparedStatement pstmt;
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
               "UPDATE xml_nodes set rootnodeid = ? " +
               "WHERE nodeid = ?");
+        // Increase DBConnection usage count
+        connection.increaseUsageCount(1);
 
         // Bind the values to the query
         pstmt.setLong(1, nodeid);
@@ -208,9 +218,11 @@
   public void writeNodename(String nodename) throws SAXException {
       try {
         PreparedStatement pstmt;
-        pstmt = conn.prepareStatement(
+        pstmt = connection.prepareStatement(
               "UPDATE xml_nodes set nodename = ? " +
               "WHERE nodeid = ?");
+        // Increase DBConnection usage count
+        connection.increaseUsageCount(1);
 
         // Bind the values to the query
         pstmt.setString(1, nodename);
@@ -229,8 +241,13 @@
   private long generateNodeID() throws SAXException {
       long nid=0;
       Statement stmt;
+      DBConnection dbConn = null;
+      int serialNumber = -1;
       try {
-        stmt = conn.createStatement();
+        // Get DBConnection
+        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
+        serialNumber=dbConn.getCheckOutSerialNumber();
+        stmt = dbConn.createStatement();
         stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
         ResultSet rs = stmt.getResultSet();
         boolean tableHasRows = rs.next();
@@ -243,6 +260,11 @@
                             e.getMessage());
         throw new SAXException(e.getMessage());
       }
+      finally
+      {
+        // Return DBconnection
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
 
       return nid;
   }
@@ -276,84 +298,8 @@
     }
   }
 
-  /** 
-   * NOT USED
-   * Update the node index (xml_index) for this node by generating
-   * test strings that represent all of the relative and absolute
-   * paths through the XML tree from document root to this node
-   */
-  private void updateNodeIndex(String docid, String doctype) 
-               throws SAXException
-  {
-    Hashtable pathlist = new Hashtable();
-    boolean atStartingNode = true;
-    boolean atRootDocumentNode = false;
-    DBSAXNode nodePointer = this;
-    StringBuffer currentPath = new StringBuffer();
-    int counter = 0;
+ 
 
-    // Create a Hashtable of all of the paths to reach this node
-    // including absolute paths and relative paths
-    while (!atRootDocumentNode) {
-      if (atStartingNode) {
-        currentPath.insert(0, nodePointer.getTagName());
-        pathlist.put(currentPath.toString(), new Long(getNodeID()));
-        counter++;
-        atStartingNode = false;
-      } else {
-        currentPath.insert(0, "/");
-        currentPath.insert(0, nodePointer.getTagName());
-        pathlist.put(currentPath.toString(), new Long(getNodeID()));
-        counter++;
-      }
-
-      // advance to the next parent node
-      nodePointer = nodePointer.getParentNode();
-
-      // If we're at the DOCUMENT node (root of DOM tree), add
-      // the root "/" to make the absolute path
-      if (nodePointer.getNodeType().equals("DOCUMENT")) {
-        currentPath.insert(0, "/");
-        pathlist.put(currentPath.toString(), new Long(getNodeID()));
-        counter++;
-        atRootDocumentNode = true;
-      } 
-    }
-
-    try {
-      // Create an insert statement to reuse for all of the path insertions
-      PreparedStatement pstmt = conn.prepareStatement(
-              "INSERT INTO xml_index (nodeid, path, docid, doctype, " + 
-               "parentnodeid) " + 
-              "VALUES (?, ?, ?, ?, ?)");
-      //((OraclePreparedStatement)pstmt).setExecuteBatch(counter);
-  
-      pstmt.setString(3, docid);
-      pstmt.setString(4, doctype);
-      pstmt.setLong(5, getParentID());
-      
-      // Step through the hashtable and insert each of the path values
-      Enumeration en = pathlist.keys();
-      while (en.hasMoreElements()) {
-        String path = (String)en.nextElement();
-        Long nodeid = (Long)pathlist.get(path);
-        pstmt.setLong(1, nodeid.longValue());
-        pstmt.setString(2, path);
-        pstmt.executeUpdate();
-  
-        //System.out.println(nodeid + " ==> " + path);
-      }
-
-      // Close the database statement
-      pstmt.close();
-    } catch (SQLException sqe) {
-      System.err.println("SQL Exception while inserting path to index in " + 
-                         "DBSAXNode.updateNodeIndex");
-      System.err.println(sqe.getMessage());
-      throw new SAXException(sqe.getMessage());
-    }
-  }
-
   /** 
    * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
    * Update the node index (xml_index) for this node by generating
@@ -360,7 +306,7 @@
    * test strings that represent all of the relative and absolute
    * paths through the XML tree from document root to this node
    */
-  public void updateNodeIndex(Connection conn, String docid, String doctype) 
+  public void updateNodeIndex(DBConnection conn, String docid, String doctype) 
                throws SAXException
   {
     Hashtable pathlist = new Hashtable();
@@ -404,6 +350,8 @@
               "INSERT INTO xml_index (nodeid, path, docid, doctype, " + 
                "parentnodeid) " + 
               "VALUES (?, ?, ?, ?, ?)");
+      // Increase usage count
+      conn.increaseUsageCount(1);
   
       pstmt.setString(3, docid);
       pstmt.setString(4, doctype);
Index: src/edu/ucsb/nceas/metacat/RelationHandler.java
===================================================================
--- src/edu/ucsb/nceas/metacat/RelationHandler.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/RelationHandler.java	(revision 1217)
@@ -27,7 +27,7 @@
 public class RelationHandler //implements Runnable
 {
   private Thread btThread = null;
-  private Connection conn = null;
+  private DBConnection connection = null;
   private String docid = null;
   MetaCatUtil util = new MetaCatUtil();
   
@@ -37,10 +37,10 @@
    * relations.
    * @param docid the ID of the XML document to index.
    */
-  public RelationHandler(String docid, Connection conn)
+  public RelationHandler(String docid, DBConnection conn)
               throws McdbException, SQLException, AccessionNumberException
   {
-    this.conn = conn;
+    this.connection = conn;
     this.docid = docid;
     putRelations();
   }
@@ -69,21 +69,26 @@
      */
 
     //DocumentImpl xmldoc = new DocumentImpl(conn,docid,false);
-    packagetype = (new DocumentImpl(conn,docid,false)).getDoctype();
+    packagetype = (new DocumentImpl(docid,false)).getDoctype();
 
     // first delete the relations for this package document if any
     deleteRelations(docid);
 
     // to put the new relations get them out of xml_nodes
-    pstmt = conn.prepareStatement(QuerySpecification.printPackageSQL(docid));
+    pstmt = connection.prepareStatement
+                                (QuerySpecification.printPackageSQL(docid));
+    //increase usage cont
+    connection.increaseUsageCount(1);
     pstmt.execute();
     ResultSet rs = pstmt.getResultSet();
     boolean hasmorerows = rs.next();
     if (hasmorerows) {
-      tstmt = conn.prepareStatement("INSERT INTO xml_relation (" +
+      tstmt = connection.prepareStatement("INSERT INTO xml_relation (" +
                                     "docid,packagetype,subject,subdoctype," +
                                     "relationship, object, objdoctype) " + 
                                     "VALUES (?, ?, ?, ?, ?, ?, ?)");
+      //increase usage count
+      connection.increaseUsageCount(1);
     }
     while(hasmorerows) {
       subject = rs.getString(1);
@@ -115,7 +120,7 @@
       tstmt.close();
     }
     pstmt.close();
-    conn.commit();
+    connection.commit();
   }
   
   /**
@@ -125,9 +130,11 @@
   public void deleteRelations(String docid) throws SQLException
   {
     try {
-      PreparedStatement pstmt = conn.prepareStatement(
+      PreparedStatement pstmt = connection.prepareStatement(
                                 "DELETE FROM xml_relation " +
                                 "WHERE docid = '" + docid + "'");
+      //increase usage count
+      connection.increaseUsageCount(1);
       pstmt.execute();
       pstmt.close();
     } catch(SQLException e) {
@@ -147,6 +154,9 @@
   public String getAccessFileID(String docid) throws SQLException
   {
     String aclid = null;
+    PreparedStatement pstmt = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     
     StringBuffer sql = new StringBuffer();
     sql.append("SELECT docid FROM xml_documents WHERE docid in (SELECT subject ");
@@ -176,14 +186,32 @@
     pstmt.setString(1, docid);
     pstmt.setString(2, MetaCatUtil.getOption("accessdoctype"));
     */
-    PreparedStatement pstmt = conn.prepareStatement(sql.toString());
-    pstmt.execute();
-    ResultSet rs = pstmt.getResultSet();
-    boolean hasRow = rs.next();
-    if (hasRow) {
-      aclid = rs.getString(1);
-    }
-    pstmt.close();
+    try
+    {
+      dbConn=DBConnectionPool.
+                  getDBConnection("RelationHandler.getAccessFileID");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement(sql.toString());
+      pstmt.execute();
+      ResultSet rs = pstmt.getResultSet();
+      boolean hasRow = rs.next();
+      if (hasRow) {
+        aclid = rs.getString(1);
+      }
+      pstmt.close();
+    }//try
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+     
     
     return aclid;
   }
Index: src/edu/ucsb/nceas/metacat/DocumentIdentifier.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DocumentIdentifier.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DocumentIdentifier.java	(revision 1217)
@@ -124,11 +124,12 @@
    */
   private String getNewestRev() throws SQLException, ClassNotFoundException
   {
-    PreparedStatement pstmt;
-    Connection conn = null;
+    PreparedStatement pstmt = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     
     try {
-      try {
+      /*try {
         //this connection is prone to error for some reason so we 
         //try to connect it three times before quiting.
         conn = util.openDBConnection();
@@ -144,9 +145,11 @@
                                sqleee.getMessage());
           }
         }
-      }
-      
-      pstmt = conn.prepareStatement("select rev from xml_documents where " +
+      }*/
+      dbConn=DBConnectionPool.
+                  getDBConnection("DocumentIdentifier.getNewestRev");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("select rev from xml_documents where " +
                                     "docid like '" + docid + "'");
       pstmt.execute();
       ResultSet rs = pstmt.getResultSet();
@@ -154,19 +157,32 @@
       if (tablehasrows) {
         String retStr = rs.getString(1);
         pstmt.close();
-        conn.close();
+        //conn.close();
         return retStr;
       }
-      conn.close();
+      //conn.close();
     } catch(SQLException e) {
       System.out.println("error in DocumentIdentifier.getNewestRev(): " +
                           e.getMessage());
-      try {
-        conn.close();
-      } catch(SQLException e2) { throw e2; }
+      /*try {
+       conn.close();
+      } catch(SQLException e2) { throw e2; }*/
       throw e;
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn,serialNumber);
+      }//finally
+    }//finally
+        
     
+    
     return "1";
   }
   
Index: src/edu/ucsb/nceas/metacat/DBUtil.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBUtil.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBUtil.java	(revision 1217)
@@ -51,7 +51,7 @@
  */
 public class DBUtil {
 
-  private Connection	conn = null;
+  //private Connection	conn = null;
 
   /**
    * main routine used for testing.
@@ -74,9 +74,9 @@
                     
           // Open a connection to the database
           MetaCatUtil   util = new MetaCatUtil();
-          Connection dbconn = util.openDBConnection();
+          //Connection dbconn = util.openDBConnection();
 
-          DBUtil dbutil = new DBUtil( dbconn );
+          DBUtil dbutil = new DBUtil();
           
           if ( args[0].equals("-dt") ) {
             String doctypes = dbutil.readDoctypes();
@@ -112,8 +112,8 @@
   /**
    * Construct an instance of the utility class
    */
-  public DBUtil( Connection conn ) {
-    this.conn = conn;
+  public DBUtil() {
+    //this.conn = conn;
   }
 
   /**
@@ -124,11 +124,16 @@
         throws SQLException  {
 
     Vector doctypeList = new Vector();
-
+    DBConnection dbConn = null;
+    int serialNumber = -1;
+    PreparedStatement pstmt = null;
     try {
 
-      PreparedStatement pstmt =
-        conn.prepareStatement("SELECT public_id FROM xml_catalog " +
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBUtil.readDoctypes");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt =
+        dbConn.prepareStatement("SELECT public_id FROM xml_catalog " +
                               "WHERE entry_type = 'DTD'");
 
       pstmt.execute();
@@ -144,6 +149,18 @@
     } catch (SQLException e) {
       throw new SQLException("DBUtil.readDoctypes(). " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
+       
 
     return formatToXML(doctypeList, "doctype");
   }
@@ -155,12 +172,17 @@
         throws SQLException, MalformedURLException, IOException
   {
     String systemID = null;
-    PreparedStatement pstmt;
+    PreparedStatement pstmt = null;
     StringBuffer cbuff = new StringBuffer();
-    
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     // get doctype's System ID from db catalog
     try {
-      pstmt = conn.prepareStatement("SELECT system_id " + 
+      
+      dbConn=DBConnectionPool.
+                  getDBConnection("DBUtil.readDTDSchema");
+      serialNumber=dbConn.getCheckOutSerialNumber();
+      pstmt = dbConn.prepareStatement("SELECT system_id " + 
                                     "FROM xml_catalog " +
                                     "WHERE entry_type in ('DTD','Schema') " +
                                     "AND public_id LIKE ?");
@@ -178,6 +200,17 @@
     } catch (SQLException e) {
       throw new SQLException("DBUtil.readDTD(). " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
 
     // read from URL stream as specified by the System ID.
     try {
@@ -220,12 +253,17 @@
 
     Vector dataguide = new Vector();
     String path;
-    PreparedStatement pstmt;
+    PreparedStatement pstmt = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     
     try {
-
+        dbConn=DBConnectionPool.
+                  getDBConnection("DBUtil.readDataGuide");
+        serialNumber=dbConn.getCheckOutSerialNumber();
+        
         if ( doctype != null ) {
-            pstmt = conn.prepareStatement("SELECT distinct path, nodeid " + 
+            pstmt = dbConn.prepareStatement("SELECT distinct path, nodeid " + 
                                           "FROM xml_index " +
                                           "WHERE path LIKE '/%' " + 
                                           "AND doctype LIKE ? " +
@@ -232,7 +270,8 @@
                                           "ORDER BY nodeid");
             pstmt.setString(1, doctype);
         } else {
-            pstmt = conn.prepareStatement("SELECT distinct path, doctype, nodeid " + 
+            pstmt = 
+            dbConn.prepareStatement("SELECT distinct path, doctype, nodeid " + 
                                           "FROM xml_index " +
                                           "WHERE path LIKE '/%' " + 
                                           "ORDER BY doctype, nodeid");
@@ -254,6 +293,17 @@
     } catch (SQLException e) {
       throw new SQLException("DBUtil.readDataGuide(). " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
 
     return formatToXML(dataguide);
   }
@@ -355,11 +405,15 @@
 
     String accnum = null;
     String sep = MetaCatUtil.getOption("accNumSeparator");
-
+    PreparedStatement pstmt = null;
+    DBConnection dbConn = null;
+    int serialNumber = -1;
     try {
-
-      PreparedStatement pstmt =
-        conn.prepareStatement(
+        dbConn=DBConnectionPool.
+                  getDBConnection("DBUtil.getMaxDocid");
+        serialNumber=dbConn.getCheckOutSerialNumber();
+        pstmt =
+        dbConn.prepareStatement(
             "SELECT docid, rev, acc FROM " +
             "( " +
             "SELECT docid, rev, acc FROM " +
@@ -402,6 +456,17 @@
     } catch (SQLException e) {
       throw new SQLException("DBUtil.getMaxDocid(). " + e.getMessage());
     }
+    finally
+    {
+      try
+      {
+        pstmt.close();
+      }//try
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }//finally
+    }//finally
 
     return accnum;
   }
Index: src/edu/ucsb/nceas/metacat/DBSimpleQuery.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBSimpleQuery.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/DBSimpleQuery.java	(revision 1217)
@@ -45,7 +45,7 @@
  */
 public class DBSimpleQuery {
 
-  private Connection	conn = null;
+  //private Connection	conn = null;
 
   /**
    * the main routine used to test the DBSimpleQuery utility.
@@ -69,10 +69,10 @@
 
           // Open a connection to the database
           MetaCatUtil   util = new MetaCatUtil();
-          Connection dbconn = util.openDBConnection();
+          //Connection dbconn = util.openDBConnection();
 
           // Execute the simple query
-          DBSimpleQuery rd = new DBSimpleQuery(dbconn);
+          DBSimpleQuery rd = new DBSimpleQuery();
           Hashtable nodelist = null;
           if (doctype.equals("any") || doctype.equals("ANY")) {
             nodelist = rd.findDocuments(query);
@@ -115,12 +115,12 @@
    *
    * @param conn the JDBC connection that we use for the query
    */
-  public DBSimpleQuery( Connection conn ) 
+  public DBSimpleQuery() 
                   throws IOException, 
                          SQLException, 
                          ClassNotFoundException
   {
-    this.conn = conn;
+    //this.conn = conn;
   }
   
   /** 
@@ -141,7 +141,9 @@
   public Hashtable findDocuments(String query, String requestedDoctype) {
       Hashtable	 docListResult = new Hashtable();
 
-      PreparedStatement pstmt;
+      PreparedStatement pstmt = null;
+      DBConnection dbConn = null;
+      int serialNumber = -1;
 
       // Now look up the document id
       String docid = null;
@@ -151,10 +153,13 @@
       //StringBuffer document = null; 
 
       try {
+        dbConn=DBConnectionPool.
+                  getDBConnection("DBSimpleQuery.findDocuments");
+        serialNumber=dbConn.getCheckOutSerialNumber();
         if (requestedDoctype == null || 
             requestedDoctype.equals("any") || 
             requestedDoctype.equals("ANY")) {
-          pstmt = conn.prepareStatement(
+          pstmt = dbConn.prepareStatement(
                 "SELECT docid,docname,doctype,doctitle " +
                 "FROM xml_documents " +
                 "WHERE docid IN " +
@@ -164,7 +169,7 @@
                 // Bind the values to the query
                 pstmt.setString(1, query);
         } else {
-          pstmt = conn.prepareStatement(
+          pstmt = dbConn.prepareStatement(
                 "SELECT docid,docname,doctype,doctitle " +
                 "FROM xml_documents " +
                 "WHERE docid IN " +
@@ -210,6 +215,10 @@
         System.out.println("Error in DBSimpleQuery.findDocuments: " + 
                             e.getMessage());
       }
+      finally
+      {
+        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+      }
 
     return docListResult;
   }
Index: src/edu/ucsb/nceas/metacat/ForceReplicationHandler.java
===================================================================
--- src/edu/ucsb/nceas/metacat/ForceReplicationHandler.java	(revision 1216)
+++ src/edu/ucsb/nceas/metacat/ForceReplicationHandler.java	(revision 1217)
@@ -48,7 +48,7 @@
 public class ForceReplicationHandler implements Runnable
 {
   private Thread btThread;
-  private Connection conn;
+  //private Connection conn;
   private MetaCatUtil util = new MetaCatUtil();
   private String docid;
   private String action;
@@ -105,9 +105,9 @@
          return;
       }
       URL comeAndGetIt = null;
-      conn = util.getConnection();
+      //conn = util.getConnection();
       // If no server in xml_replication table, metacat don't need do anything
-      if (ReplicationHandler.buildServerList(conn)==null)
+      if (ReplicationHandler.buildServerList()==null)
       {
         return;
       }
@@ -177,7 +177,7 @@
         //the URL never directly replies to the request.  this simply
         //invoces a read request from the server to this local machine.
       }//while
-      util.returnConnection(conn);
+      //util.returnConnection(conn);
     }//try
     catch(Exception e)
     {
