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 2358 sgarg
/**
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 2358 sgarg
  /**
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 2358 sgarg
  /**
64 136 jones
   * 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 2358 sgarg
                    DBSAXNode parentNode, long rootnodeid,
72
                    String docid, String doctype)
73 826 bojilova
                                               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 2358 sgarg
87
  /**
88 1803 tao
   * Construct a new node instance for DTD nodes
89
   * This Node will write docname, publicId and systemId into db. Only
90
   * handle systemid  existed.(external dtd)
91
   *
92
   * @param conn the JDBC Connection to which all information is written
93
   * @param tagname the name of the node
94
   * @param parentNode the parent node for this node being created
95
   */
96 2358 sgarg
  public DBSAXNode (DBConnection conn, String docName, String publicId,
97
                    String systemId, DBSAXNode parentNode, long rootnodeid,
98
                    String docid) throws SAXException
99 1803 tao
  {
100
101
    super();
102
    this.connection = conn;
103
    this.parentNode = parentNode;
104
    setParentID(parentNode.getNodeID());
105
    setRootNodeID(rootnodeid);
106
    setDocID(docid);
107
    // insert dtd node only for external dtd definiation
108
    if (systemId != null)
109
    {
110
      //write docname to DB
111
      if (docName != null)
112
      {
113
        setNodeIndex(parentNode.incChildNum());
114
        writeDTDNodeToDB(DocumentImpl.DOCNAME, docName, docid);
115
      }
116
      //write publicId to DB
117
      if (publicId != null)
118
      {
119
        setNodeIndex(parentNode.incChildNum());
120
        writeDTDNodeToDB(DocumentImpl.PUBLICID, publicId, docid);
121
      }
122
      //write systemId to DB
123
      setNodeIndex(parentNode.incChildNum());
124
      writeDTDNodeToDB(DocumentImpl.SYSTEMID, systemId, docid);
125
    }
126
  }
127 2358 sgarg
128 133 jones
  /** creates SQL code and inserts new node into DB connection */
129 1416 tao
  public long writeChildNodeToDB(String nodetype, String nodename,
130 2358 sgarg
                                 String data, String docid)
131
                                 throws SAXException
132 1416 tao
  {
133
    long nid = -1;
134 2358 sgarg
    try
135 1416 tao
    {
136 2358 sgarg
137 133 jones
      PreparedStatement pstmt;
138 2358 sgarg
139 133 jones
      if (nodetype == "DOCUMENT") {
140 1217 tao
        pstmt = connection.prepareStatement(
141 133 jones
            "INSERT INTO xml_nodes " +
142 826 bojilova
            "(nodetype, nodename, nodeprefix, docid) " +
143
            "VALUES (?, ?, ?, ?)");
144 2358 sgarg
145 1217 tao
        // Increase DBConnection usage count
146
        connection.increaseUsageCount(1);
147 1495 tao
        MetaCatUtil.debugMessage("INSERTING DOCNAME: " + nodename, 35);
148 133 jones
      } else {
149 2364 sgarg
          if(data != null && !data.trim().equals("")
150
             && !data.trim().equals("NaN")){
151 2358 sgarg
              try{
152
                  double numberData = Double.parseDouble(data);
153
                  pstmt = connection.prepareStatement(
154
                      "INSERT INTO xml_nodes " +
155
                      "(nodetype, nodename, nodeprefix, docid, " +
156
                      "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
157
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
158
              } catch (NumberFormatException nfe) {
159
                  pstmt = connection.prepareStatement(
160
                      "INSERT INTO xml_nodes " +
161
                      "(nodetype, nodename, nodeprefix, docid, " +
162
                      "rootnodeid, parentnodeid, nodedata, nodeindex) " +
163
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
164
              }
165
          } else {
166
              pstmt = connection.prepareStatement(
167
                  "INSERT INTO xml_nodes " +
168
                  "(nodetype, nodename, nodeprefix, docid, " +
169
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
170
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
171
          }
172 1217 tao
        // Increase DBConnection usage count
173
        connection.increaseUsageCount(1);
174 133 jones
      }
175 19 jones
176 133 jones
      // Bind the values to the query
177 758 bojilova
      pstmt.setString(1, nodetype);
178 826 bojilova
      int idx;
179
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
180
        pstmt.setString(2, nodename.substring(idx+1));
181
        pstmt.setString(3, nodename.substring(0,idx));
182
      } else {
183
        pstmt.setString(2, nodename);
184
        pstmt.setString(3, null);
185
      }
186
      pstmt.setString(4, docid);
187 408 jones
      if (nodetype == "DOCUMENT") {
188 758 bojilova
        // moved it to separate method updateRootNodeID
189
        //pstmt.setLong(4, nid);
190 408 jones
      } else {
191 133 jones
        if (nodetype == "ELEMENT") {
192 826 bojilova
          pstmt.setLong(5, getRootNodeID());
193
          pstmt.setLong(6, getParentID());
194
          pstmt.setString(7, data);
195
          pstmt.setInt(8, getNodeIndex());
196 133 jones
        } else {
197 826 bojilova
          pstmt.setLong(5, getRootNodeID());
198
          pstmt.setLong(6, getNodeID());
199
          pstmt.setString(7, data);
200
          pstmt.setInt(8, incChildNum());
201 72 bojilova
        }
202 133 jones
      }
203
      // Do the insertion
204
      pstmt.execute();
205
      pstmt.close();
206 758 bojilova
207
      // get the generated unique id afterward
208 1416 tao
      nid = dbAdapter.getUniqueID(connection.getConnections(), "xml_nodes");
209 1217 tao
      //should incease connection usage!!!!!!
210 2358 sgarg
211
212 408 jones
      if (nodetype.equals("DOCUMENT")) {
213
        // Record the root node id that was generated from the database
214
        setRootNodeID(nid);
215
      }
216
217 177 jones
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
218 176 jones
219 177 jones
        // Record the node id that was generated from the database
220
        setNodeID(nid);
221 176 jones
222 177 jones
        // Record the node type that was passed to the method
223
        setNodeType(nodetype);
224
225
      }
226
227 133 jones
    } catch (SQLException e) {
228 675 berkley
      System.out.println("Error in DBSaxNode.writeChildNodeToDB");
229 133 jones
      System.err.println("Error inserting node: (" + nodetype + ", " +
230 2358 sgarg
                                                     nodename + ", " +
231 136 jones
                                                     data + ")" );
232 133 jones
      System.err.println(e.getMessage());
233 915 berkley
      e.printStackTrace(System.err);
234 461 bojilova
      throw new SAXException(e.getMessage());
235 110 bojilova
    }
236 1416 tao
    return nid;
237 133 jones
  }
238 110 bojilova
239 2358 sgarg
  /**
240 758 bojilova
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
241
   */
242
  public void updateRootNodeID(long nodeid) throws SAXException {
243
      try {
244
        PreparedStatement pstmt;
245 1217 tao
        pstmt = connection.prepareStatement(
246 758 bojilova
              "UPDATE xml_nodes set rootnodeid = ? " +
247
              "WHERE nodeid = ?");
248 1217 tao
        // Increase DBConnection usage count
249
        connection.increaseUsageCount(1);
250 758 bojilova
251
        // Bind the values to the query
252
        pstmt.setLong(1, nodeid);
253
        pstmt.setLong(2, nodeid);
254
        // Do the update
255
        pstmt.execute();
256
        pstmt.close();
257
      } catch (SQLException e) {
258 2358 sgarg
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
259 758 bojilova
                           e.getMessage());
260
        throw new SAXException(e.getMessage());
261
      }
262
  }
263
264 2358 sgarg
  /**
265
   * creates SQL code to put nodename for the document node
266
   * into DB connection
267 133 jones
   */
268 461 bojilova
  public void writeNodename(String nodename) throws SAXException {
269 133 jones
      try {
270
        PreparedStatement pstmt;
271 1217 tao
        pstmt = connection.prepareStatement(
272 133 jones
              "UPDATE xml_nodes set nodename = ? " +
273
              "WHERE nodeid = ?");
274 1217 tao
        // Increase DBConnection usage count
275
        connection.increaseUsageCount(1);
276 16 jones
277 133 jones
        // Bind the values to the query
278
        pstmt.setString(1, nodename);
279 134 jones
        pstmt.setLong(2, getNodeID());
280 133 jones
        // Do the insertion
281
        pstmt.execute();
282
        pstmt.close();
283
      } catch (SQLException e) {
284 2358 sgarg
        System.out.println("Error in DBSaxNode.writeNodeName: " +
285 675 berkley
                           e.getMessage());
286 461 bojilova
        throw new SAXException(e.getMessage());
287 133 jones
      }
288
  }
289 16 jones
290 1803 tao
 /** creates SQL code and inserts new node into DB connection */
291 2358 sgarg
  public long writeDTDNodeToDB(String nodename, String data, String docid)
292
                                 throws SAXException
293 1803 tao
  {
294
    long nid = -1;
295 2358 sgarg
    try
296 1803 tao
    {
297 2358 sgarg
298 1803 tao
      PreparedStatement pstmt;
299
      MetaCatUtil.debugMessage("Insert dtd into db: "+nodename +" "+data, 45);
300 2358 sgarg
      if(data != null && !data.trim().equals("")){
301
            try{
302
                double numberData = Double.parseDouble(data);
303
                pstmt = connection.prepareStatement(
304
                    "INSERT INTO xml_nodes " +
305
                    "(nodetype, nodename, docid, " +
306
                    "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
307
                    "VALUES (?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
308
            } catch (NumberFormatException nfe) {
309
                pstmt = connection.prepareStatement(
310
                    "INSERT INTO xml_nodes " +
311
                    "(nodetype, nodename,  docid, " +
312
                    "rootnodeid, parentnodeid, nodedata, nodeindex) " +
313
                    "VALUES (?, ?, ?, ?, ?, ?, ?)");
314
            }
315
        } else {
316
            pstmt = connection.prepareStatement(
317
                  "INSERT INTO xml_nodes " +
318
                  "(nodetype, nodename, docid, " +
319
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
320
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
321
        }
322
323 1803 tao
       // Increase DBConnection usage count
324
      connection.increaseUsageCount(1);
325 2358 sgarg
326 1803 tao
      // Bind the values to the query
327
      pstmt.setString(1, DocumentImpl.DTD);
328
      pstmt.setString(2, nodename);
329
      pstmt.setString(3, docid);
330
      pstmt.setLong(4, getRootNodeID());
331
      pstmt.setLong(5, getParentID());
332
      pstmt.setString(6, data);
333
      pstmt.setInt(7, getNodeIndex());
334 2358 sgarg
335 1803 tao
      // Do the insertion
336
      pstmt.execute();
337
      pstmt.close();
338
339
      // get the generated unique id afterward
340
      nid = dbAdapter.getUniqueID(connection.getConnections(), "xml_nodes");
341
      //should incease connection usage!!!!!!
342 2358 sgarg
343 1803 tao
    } catch (SQLException e) {
344
      System.out.println("Error in DBSaxNode.writeDTDNodeToDB");
345
      System.err.println("Error inserting node: (" + DocumentImpl.DTD + ", " +
346 2358 sgarg
                                                     nodename + ", " +
347 1803 tao
                                                     data + ")" );
348
      System.err.println(e.getMessage());
349
      e.printStackTrace(System.err);
350
      throw new SAXException(e.getMessage());
351
    }
352
    return nid;
353
  }
354 2358 sgarg
355
356 174 bojilova
  /** get next node id from DB connection */
357 461 bojilova
  private long generateNodeID() throws SAXException {
358 174 bojilova
      long nid=0;
359 133 jones
      Statement stmt;
360 1217 tao
      DBConnection dbConn = null;
361
      int serialNumber = -1;
362 133 jones
      try {
363 1217 tao
        // Get DBConnection
364
        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
365
        serialNumber=dbConn.getCheckOutSerialNumber();
366
        stmt = dbConn.createStatement();
367 174 bojilova
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
368 133 jones
        ResultSet rs = stmt.getResultSet();
369
        boolean tableHasRows = rs.next();
370
        if (tableHasRows) {
371 174 bojilova
          nid = rs.getLong(1);
372 19 jones
        }
373 133 jones
        stmt.close();
374
      } catch (SQLException e) {
375 2358 sgarg
        System.out.println("Error in DBSaxNode.generateNodeID: " +
376 675 berkley
                            e.getMessage());
377 461 bojilova
        throw new SAXException(e.getMessage());
378 15 jones
      }
379 1217 tao
      finally
380
      {
381
        // Return DBconnection
382
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
383
      }//finally
384 15 jones
385 174 bojilova
      return nid;
386 133 jones
  }
387 18 jones
388 137 jones
  /** Add a new attribute to this node, or set its value */
389 1416 tao
  public long setAttribute(String attName, String attValue, String docid)
390 2358 sgarg
              throws SAXException
391 1416 tao
  {
392
    long nodeId = -1;
393 2358 sgarg
    if (attName != null)
394 1416 tao
    {
395 133 jones
      // Enter the attribute in the hash table
396
      super.setAttribute(attName, attValue);
397 18 jones
398 133 jones
      // And enter the attribute in the database
399 1416 tao
      nodeId = writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
400 2358 sgarg
    }
401
    else
402 1416 tao
    {
403 133 jones
      System.err.println("Attribute name must not be null!");
404 461 bojilova
      throw new SAXException("Attribute name must not be null!");
405 18 jones
    }
406 1416 tao
    return nodeId;
407 133 jones
  }
408 176 jones
409 821 bojilova
  /** Add a namespace to this node */
410 1416 tao
  public long setNamespace(String prefix, String uri, String docid)
411 2358 sgarg
              throws SAXException
412 1416 tao
  {
413
    long nodeId = -1;
414 2358 sgarg
    if (prefix != null)
415 1416 tao
    {
416 821 bojilova
      // Enter the namespace in a hash table
417
      super.setNamespace(prefix, uri);
418
      // And enter the namespace in the database
419 1416 tao
      nodeId = writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
420 2358 sgarg
    }
421
    else
422 1416 tao
    {
423 821 bojilova
      System.err.println("Namespace prefix must not be null!");
424
      throw new SAXException("Namespace prefix must not be null!");
425
    }
426 1416 tao
    return nodeId;
427 821 bojilova
  }
428
429 176 jones
430 2358 sgarg
431
  /**
432 471 bojilova
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
433
   * Update the node index (xml_index) for this node by generating
434
   * test strings that represent all of the relative and absolute
435
   * paths through the XML tree from document root to this node
436
   */
437 2358 sgarg
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
438 471 bojilova
               throws SAXException
439
  {
440
    Hashtable pathlist = new Hashtable();
441
    boolean atStartingNode = true;
442
    boolean atRootDocumentNode = false;
443
    DBSAXNode nodePointer = this;
444
    StringBuffer currentPath = new StringBuffer();
445
    int counter = 0;
446
447
    // Create a Hashtable of all of the paths to reach this node
448
    // including absolute paths and relative paths
449
    while (!atRootDocumentNode) {
450
      if (atStartingNode) {
451
        currentPath.insert(0, nodePointer.getTagName());
452
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
453
        counter++;
454
        atStartingNode = false;
455
      } else {
456
        currentPath.insert(0, "/");
457
        currentPath.insert(0, nodePointer.getTagName());
458
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
459
        counter++;
460
      }
461
462
      // advance to the next parent node
463
      nodePointer = nodePointer.getParentNode();
464
465
      // If we're at the DOCUMENT node (root of DOM tree), add
466
      // the root "/" to make the absolute path
467
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
468
        currentPath.insert(0, "/");
469
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
470
        counter++;
471
        atRootDocumentNode = true;
472 2358 sgarg
      }
473 471 bojilova
    }
474
475
    try {
476
      // Create an insert statement to reuse for all of the path insertions
477
      PreparedStatement pstmt = conn.prepareStatement(
478 2358 sgarg
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " +
479
               "parentnodeid) " +
480 471 bojilova
              "VALUES (?, ?, ?, ?, ?)");
481 1217 tao
      // Increase usage count
482
      conn.increaseUsageCount(1);
483 2358 sgarg
484 471 bojilova
      pstmt.setString(3, docid);
485
      pstmt.setString(4, doctype);
486
      pstmt.setLong(5, getParentID());
487 2358 sgarg
488 471 bojilova
      // Step through the hashtable and insert each of the path values
489 176 jones
      Enumeration en = pathlist.keys();
490
      while (en.hasMoreElements()) {
491
        String path = (String)en.nextElement();
492
        Long nodeid = (Long)pathlist.get(path);
493
        pstmt.setLong(1, nodeid.longValue());
494
        pstmt.setString(2, path);
495 2358 sgarg
496 457 bojilova
        pstmt.executeUpdate();
497 176 jones
      }
498
      // Close the database statement
499
      pstmt.close();
500
    } catch (SQLException sqe) {
501 675 berkley
      System.err.println("SQL Exception while inserting path to index in " +
502 899 berkley
                         "DBSAXNode.updateNodeIndex for document " + docid);
503 176 jones
      System.err.println(sqe.getMessage());
504 461 bojilova
      throw new SAXException(sqe.getMessage());
505 176 jones
    }
506
  }
507 2358 sgarg
508 176 jones
  /** get the parent of this node */
509
  public DBSAXNode getParentNode() {
510
    return parentNode;
511
  }
512 15 jones
}