Project

General

Profile

1 15 jones
/**
2 203 jones
 *  '$RCSfile$'
3
 *    Purpose: A Class that represents an XML node and its contents
4
 *  Copyright: 2000 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Matt Jones
7 349 jones
 *    Release: @release@
8 15 jones
 *
9 203 jones
 *   '$Author$'
10
 *     '$Date$'
11
 * '$Revision$'
12 669 jones
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 15 jones
 */
27
28 75 jones
package edu.ucsb.nceas.metacat;
29 15 jones
30
import java.sql.*;
31
import java.io.IOException;
32
import java.util.Hashtable;
33
import java.util.Enumeration;
34 763 bojilova
//import oracle.jdbc.driver.*;
35 461 bojilova
import org.xml.sax.SAXException;
36 15 jones
37 777 bojilova
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
38 747 bojilova
39 31 jones
/**
40 137 jones
 * A Class that represents an XML node and its contents and
41 31 jones
 * can write its own representation to a database connection
42
 */
43 137 jones
public class DBSAXNode extends BasicNode {
44 15 jones
45 1217 tao
  private DBConnection	connection;
46 176 jones
  private DBSAXNode	parentNode;
47 777 bojilova
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
48 15 jones
49 133 jones
  /**
50 136 jones
   * Construct a new node instance for DOCUMENT nodes
51 133 jones
   *
52
   * @param conn the JDBC Connection to which all information is written
53
   */
54 1217 tao
  public DBSAXNode (DBConnection conn, String docid) throws SAXException {
55 747 bojilova
56 408 jones
    super();
57 1217 tao
    this.connection = conn;
58 176 jones
    this.parentNode = null;
59 457 bojilova
    writeChildNodeToDB("DOCUMENT", null, null, docid);
60 758 bojilova
    updateRootNodeID(getNodeID());
61 136 jones
  }
62
63
  /**
64
   * Construct a new node instance for ELEMENT nodes
65
   *
66
   * @param conn the JDBC Connection to which all information is written
67
   * @param tagname the name of the node
68
   * @param parentNode the parent node for this node being created
69
   */
70 1217 tao
  public DBSAXNode (DBConnection conn, String qName, String lName,
71 826 bojilova
                    DBSAXNode parentNode, long rootnodeid,
72
                    String docid, String doctype)
73
                                               throws SAXException {
74 21 jones
75 826 bojilova
    super(lName);
76 1217 tao
    this.connection = conn;
77 747 bojilova
    this.parentNode = parentNode;
78 136 jones
    setParentID(parentNode.getNodeID());
79 457 bojilova
    setRootNodeID(rootnodeid);
80
    setDocID(docid);
81 136 jones
    setNodeIndex(parentNode.incChildNum());
82 826 bojilova
    writeChildNodeToDB("ELEMENT", qName, null, docid);
83 471 bojilova
    //No writing XML Index from here. New Thread used instead.
84
    //updateNodeIndex(docid, doctype);
85 133 jones
  }
86 15 jones
87 133 jones
  /** creates SQL code and inserts new node into DB connection */
88
  public void writeChildNodeToDB(String nodetype, String nodename,
89 461 bojilova
                                 String data, String docid)
90
                                 throws SAXException {
91 133 jones
    try {
92 1217 tao
      /*if(conn == null)
93 1001 berkley
      {
94
        try
95
        {
96
          MetaCatUtil util = new MetaCatUtil();
97
          conn = util.getConnection();
98
        }
99
        catch(Exception e)
100
        {
101
          MetaCatUtil.debug("Error while getting db connection in " +
102
                            "DBSAXNode: " + e.getMessage());
103
        }
104 1217 tao
      }*/
105 1001 berkley
106 133 jones
      PreparedStatement pstmt;
107
      if (nodetype == "DOCUMENT") {
108 1217 tao
        pstmt = connection.prepareStatement(
109 133 jones
            "INSERT INTO xml_nodes " +
110 826 bojilova
            "(nodetype, nodename, nodeprefix, docid) " +
111
            "VALUES (?, ?, ?, ?)");
112 1217 tao
113
        // Increase DBConnection usage count
114
        connection.increaseUsageCount(1);
115 204 jones
        MetaCatUtil.debugMessage("INSERTING DOCNAME: " + nodename);
116 133 jones
      } else {
117 1217 tao
        pstmt = connection.prepareStatement(
118 133 jones
            "INSERT INTO xml_nodes " +
119 826 bojilova
            "(nodetype, nodename, nodeprefix, docid, " +
120 457 bojilova
            "rootnodeid, parentnodeid, nodedata, nodeindex) " +
121 826 bojilova
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
122 1217 tao
        // Increase DBConnection usage count
123
        connection.increaseUsageCount(1);
124 133 jones
      }
125 19 jones
126 133 jones
      // Bind the values to the query
127 758 bojilova
      pstmt.setString(1, nodetype);
128 826 bojilova
      int idx;
129
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
130
        pstmt.setString(2, nodename.substring(idx+1));
131
        pstmt.setString(3, nodename.substring(0,idx));
132
      } else {
133
        pstmt.setString(2, nodename);
134
        pstmt.setString(3, null);
135
      }
136
      pstmt.setString(4, docid);
137 408 jones
      if (nodetype == "DOCUMENT") {
138 758 bojilova
        // moved it to separate method updateRootNodeID
139
        //pstmt.setLong(4, nid);
140 408 jones
      } else {
141 133 jones
        if (nodetype == "ELEMENT") {
142 826 bojilova
          pstmt.setLong(5, getRootNodeID());
143
          pstmt.setLong(6, getParentID());
144
          pstmt.setString(7, data);
145
          pstmt.setInt(8, getNodeIndex());
146 133 jones
        } else {
147 826 bojilova
          pstmt.setLong(5, getRootNodeID());
148
          pstmt.setLong(6, getNodeID());
149
          pstmt.setString(7, data);
150
          pstmt.setInt(8, incChildNum());
151 72 bojilova
        }
152 133 jones
      }
153
      // Do the insertion
154
      pstmt.execute();
155
      pstmt.close();
156 758 bojilova
157
      // get the generated unique id afterward
158 1217 tao
      long nid = dbAdapter.
159
                         getUniqueID(connection.getConnections(), "xml_nodes");
160
      //should incease connection usage!!!!!!
161
162 174 bojilova
163 408 jones
      if (nodetype.equals("DOCUMENT")) {
164
        // Record the root node id that was generated from the database
165
        setRootNodeID(nid);
166
      }
167
168 177 jones
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
169 176 jones
170 177 jones
        // Record the node id that was generated from the database
171
        setNodeID(nid);
172 176 jones
173 177 jones
        // Record the node type that was passed to the method
174
        setNodeType(nodetype);
175
176
      }
177
178 133 jones
    } catch (SQLException e) {
179 675 berkley
      System.out.println("Error in DBSaxNode.writeChildNodeToDB");
180 133 jones
      System.err.println("Error inserting node: (" + nodetype + ", " +
181
                                                     nodename + ", " +
182 136 jones
                                                     data + ")" );
183 133 jones
      System.err.println(e.getMessage());
184 915 berkley
      e.printStackTrace(System.err);
185 461 bojilova
      throw new SAXException(e.getMessage());
186 110 bojilova
    }
187 133 jones
  }
188 110 bojilova
189 133 jones
  /**
190 758 bojilova
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
191
   */
192
  public void updateRootNodeID(long nodeid) throws SAXException {
193
      try {
194
        PreparedStatement pstmt;
195 1217 tao
        pstmt = connection.prepareStatement(
196 758 bojilova
              "UPDATE xml_nodes set rootnodeid = ? " +
197
              "WHERE nodeid = ?");
198 1217 tao
        // Increase DBConnection usage count
199
        connection.increaseUsageCount(1);
200 758 bojilova
201
        // Bind the values to the query
202
        pstmt.setLong(1, nodeid);
203
        pstmt.setLong(2, nodeid);
204
        // Do the update
205
        pstmt.execute();
206
        pstmt.close();
207
      } catch (SQLException e) {
208
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
209
                           e.getMessage());
210
        throw new SAXException(e.getMessage());
211
      }
212
  }
213
214
  /**
215 133 jones
   * creates SQL code to put nodename for the document node
216
   * into DB connection
217
   */
218 461 bojilova
  public void writeNodename(String nodename) throws SAXException {
219 133 jones
      try {
220
        PreparedStatement pstmt;
221 1217 tao
        pstmt = connection.prepareStatement(
222 133 jones
              "UPDATE xml_nodes set nodename = ? " +
223
              "WHERE nodeid = ?");
224 1217 tao
        // Increase DBConnection usage count
225
        connection.increaseUsageCount(1);
226 16 jones
227 133 jones
        // Bind the values to the query
228
        pstmt.setString(1, nodename);
229 134 jones
        pstmt.setLong(2, getNodeID());
230 133 jones
        // Do the insertion
231
        pstmt.execute();
232
        pstmt.close();
233
      } catch (SQLException e) {
234 675 berkley
        System.out.println("Error in DBSaxNode.writeNodeName: " +
235
                           e.getMessage());
236 461 bojilova
        throw new SAXException(e.getMessage());
237 133 jones
      }
238
  }
239 16 jones
240 174 bojilova
  /** get next node id from DB connection */
241 461 bojilova
  private long generateNodeID() throws SAXException {
242 174 bojilova
      long nid=0;
243 133 jones
      Statement stmt;
244 1217 tao
      DBConnection dbConn = null;
245
      int serialNumber = -1;
246 133 jones
      try {
247 1217 tao
        // Get DBConnection
248
        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
249
        serialNumber=dbConn.getCheckOutSerialNumber();
250
        stmt = dbConn.createStatement();
251 174 bojilova
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
252 133 jones
        ResultSet rs = stmt.getResultSet();
253
        boolean tableHasRows = rs.next();
254
        if (tableHasRows) {
255 174 bojilova
          nid = rs.getLong(1);
256 19 jones
        }
257 133 jones
        stmt.close();
258
      } catch (SQLException e) {
259 675 berkley
        System.out.println("Error in DBSaxNode.generateNodeID: " +
260
                            e.getMessage());
261 461 bojilova
        throw new SAXException(e.getMessage());
262 15 jones
      }
263 1217 tao
      finally
264
      {
265
        // Return DBconnection
266
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
267
      }//finally
268 15 jones
269 174 bojilova
      return nid;
270 133 jones
  }
271 18 jones
272 137 jones
  /** Add a new attribute to this node, or set its value */
273 461 bojilova
  public void setAttribute(String attName, String attValue, String docid)
274
              throws SAXException {
275 133 jones
    if (attName != null) {
276
      // Enter the attribute in the hash table
277
      super.setAttribute(attName, attValue);
278 18 jones
279 133 jones
      // And enter the attribute in the database
280 457 bojilova
      writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
281 133 jones
    } else {
282
      System.err.println("Attribute name must not be null!");
283 461 bojilova
      throw new SAXException("Attribute name must not be null!");
284 18 jones
    }
285 133 jones
  }
286 176 jones
287 821 bojilova
  /** Add a namespace to this node */
288
  public void setNamespace(String prefix, String uri, String docid)
289
              throws SAXException {
290
    if (prefix != null) {
291
      // Enter the namespace in a hash table
292
      super.setNamespace(prefix, uri);
293
      // And enter the namespace in the database
294
      writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
295
    } else {
296
      System.err.println("Namespace prefix must not be null!");
297
      throw new SAXException("Namespace prefix must not be null!");
298
    }
299
  }
300
301 1217 tao
302 176 jones
303 471 bojilova
  /**
304
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
305
   * Update the node index (xml_index) for this node by generating
306
   * test strings that represent all of the relative and absolute
307
   * paths through the XML tree from document root to this node
308
   */
309 1217 tao
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
310 471 bojilova
               throws SAXException
311
  {
312
    Hashtable pathlist = new Hashtable();
313
    boolean atStartingNode = true;
314
    boolean atRootDocumentNode = false;
315
    DBSAXNode nodePointer = this;
316
    StringBuffer currentPath = new StringBuffer();
317
    int counter = 0;
318
319
    // Create a Hashtable of all of the paths to reach this node
320
    // including absolute paths and relative paths
321
    while (!atRootDocumentNode) {
322
      if (atStartingNode) {
323
        currentPath.insert(0, nodePointer.getTagName());
324
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
325
        counter++;
326
        atStartingNode = false;
327
      } else {
328
        currentPath.insert(0, "/");
329
        currentPath.insert(0, nodePointer.getTagName());
330
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
331
        counter++;
332
      }
333
334
      // advance to the next parent node
335
      nodePointer = nodePointer.getParentNode();
336
337
      // If we're at the DOCUMENT node (root of DOM tree), add
338
      // the root "/" to make the absolute path
339
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
340
        currentPath.insert(0, "/");
341
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
342
        counter++;
343
        atRootDocumentNode = true;
344
      }
345
    }
346
347
    try {
348
      // Create an insert statement to reuse for all of the path insertions
349
      PreparedStatement pstmt = conn.prepareStatement(
350
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " +
351
               "parentnodeid) " +
352
              "VALUES (?, ?, ?, ?, ?)");
353 1217 tao
      // Increase usage count
354
      conn.increaseUsageCount(1);
355 471 bojilova
356
      pstmt.setString(3, docid);
357
      pstmt.setString(4, doctype);
358
      pstmt.setLong(5, getParentID());
359
360
      // Step through the hashtable and insert each of the path values
361 176 jones
      Enumeration en = pathlist.keys();
362
      while (en.hasMoreElements()) {
363
        String path = (String)en.nextElement();
364
        Long nodeid = (Long)pathlist.get(path);
365
        pstmt.setLong(1, nodeid.longValue());
366
        pstmt.setString(2, path);
367 899 berkley
368 457 bojilova
        pstmt.executeUpdate();
369 176 jones
      }
370
      // Close the database statement
371
      pstmt.close();
372
    } catch (SQLException sqe) {
373 675 berkley
      System.err.println("SQL Exception while inserting path to index in " +
374 899 berkley
                         "DBSAXNode.updateNodeIndex for document " + docid);
375 176 jones
      System.err.println(sqe.getMessage());
376 461 bojilova
      throw new SAXException(sqe.getMessage());
377 176 jones
    }
378
  }
379
380
  /** get the parent of this node */
381
  public DBSAXNode getParentNode() {
382
    return parentNode;
383
  }
384 15 jones
}