Example 6-21: Handling the insert for a single web access log entry

import java.net.URL;
import java.sql.*;
import org.w3c.dom.Document;
import java.sql.Connection;
import oracle.xml.parser.v2.XMLDocument;
import java.sql.Date;

public class LogEntryInsertHandler implements XMLDocumentHandler{
  private Connection conn;
  private CallableStatement cs;
  private long rows = 0;
  private long commitBatch = 10;
  // Remember the commit-batch quantity and database connection
  public LogEntryInsertHandler(Connection conn, long commitBatch)
                               throws SQLException {
    this.commitBatch = commitBatch;
    this.conn = conn;
    setupCallableStatement();
  }
  // Return number of rows processed so far
  public long getRowsHandled() { return rows; }
  // Handle the processing of a single <req> document
  public void handleDocument( Document doc , URL u ) throws Exception {
    XMLDocument d = (XMLDocument)doc;
    // Bump the row counter
    rows++;
    // Bind the values for the insert from values of XPath over current doc
    cs.setString(1,d.valueOf("/req/@h")); // host
    cs.setString(2,d.valueOf("/req/@r")); // request made
    cs.setString(3,d.valueOf("/req/@t")); // time of request
    cs.setString(4,d.valueOf("/req/@f")); // referred from
    cs.setString(5,d.valueOf("/req/@u")); // user agent
    // Do the insert
    cs.execute();
    if (rows % commitBatch == 0) {
      // Commit every 'commitBatch' rows
      conn.commit();
    }
  }
  // Setup reusable statement for inserts
  private void setupCallableStatement() throws SQLException {
    if (cs != null) {
      try { cs.close(); }
      catch (SQLException s) {}
    }
    cs = conn.prepareCall("INSERT INTO access_log VALUES(?,?,?,?,?)");
  }
  // Commit any uncommitted rows, and close statement and connection.
  protected void finalize() throws Throwable {
    try { conn.commit(); } catch (SQLException s) {}
    try { cs.close();    } catch (SQLException s) {}
    try { conn.close();  } catch (SQLException s) {}
  }
}