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 15 jones
 *
8 203 jones
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
11 669 jones
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25 15 jones
 */
26
27 75 jones
package edu.ucsb.nceas.metacat;
28 15 jones
29
import java.sql.*;
30
import java.util.Hashtable;
31
import java.util.Enumeration;
32 2663 sgarg
import org.apache.log4j.Logger;
33 461 bojilova
import org.xml.sax.SAXException;
34 15 jones
35 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
36
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
37
import edu.ucsb.nceas.metacat.database.DatabaseService;
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 2663 sgarg
  private Logger logMetacat = Logger.getLogger(DBSAXNode.class);
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 5208 daigle
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 5208 daigle
                                 throws SAXException {
132
    String limitedData = null;
133
    int leftover = 0;
134
    if (data != null) {
135
    	leftover = data.length();
136
    }
137
    int offset = 0;
138
    boolean moredata = true;
139
    long endNodeId = -1;
140
141
    // This loop deals with the case where there are more characters
142
    // than can fit in a single database text field (limit is
143
    // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
144
    // write a series of nodes that are MAXDATACHARS long, and then the
145
    // final node contains the remainder
146
    while (moredata) {
147
        if (leftover > DBSAXHandler.MAXDATACHARS) {
148
        	limitedData = data.substring(offset, DBSAXHandler.MAXDATACHARS);
149
            leftover -= DBSAXHandler.MAXDATACHARS;
150
            offset += DBSAXHandler.MAXDATACHARS;
151
        } else {
152
        	limitedData = data;
153
            moredata = false;
154
        }
155
        endNodeId =  writeChildNodeToDBDataLimited(nodetype, nodename,
156
              limitedData, docid);
157
    }
158
159
    return endNodeId;
160
  }
161
162
  /** creates SQL code and inserts new node into DB connection */
163
  public long writeChildNodeToDBDataLimited(String nodetype, String nodename,
164
                                 String data, String docid)
165 2358 sgarg
                                 throws SAXException
166 1416 tao
  {
167
    long nid = -1;
168 2358 sgarg
    try
169 1416 tao
    {
170 2358 sgarg
171 133 jones
      PreparedStatement pstmt;
172 2358 sgarg
173 133 jones
      if (nodetype == "DOCUMENT") {
174 1217 tao
        pstmt = connection.prepareStatement(
175 133 jones
            "INSERT INTO xml_nodes " +
176 826 bojilova
            "(nodetype, nodename, nodeprefix, docid) " +
177
            "VALUES (?, ?, ?, ?)");
178 2358 sgarg
179 1217 tao
        // Increase DBConnection usage count
180
        connection.increaseUsageCount(1);
181 5208 daigle
        logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - inserting doc name: " + nodename);
182 133 jones
      } else {
183 2364 sgarg
          if(data != null && !data.trim().equals("")
184 3197 tao
             && !data.trim().equals("NaN") && !data.trim().equalsIgnoreCase("Infinity")){
185 2358 sgarg
              try{
186
                  double numberData = Double.parseDouble(data);
187
                  pstmt = connection.prepareStatement(
188
                      "INSERT INTO xml_nodes " +
189
                      "(nodetype, nodename, nodeprefix, docid, " +
190
                      "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
191
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
192
              } catch (NumberFormatException nfe) {
193
                  pstmt = connection.prepareStatement(
194
                      "INSERT INTO xml_nodes " +
195
                      "(nodetype, nodename, nodeprefix, docid, " +
196
                      "rootnodeid, parentnodeid, nodedata, nodeindex) " +
197
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
198
              }
199
          } else {
200
              pstmt = connection.prepareStatement(
201
                  "INSERT INTO xml_nodes " +
202
                  "(nodetype, nodename, nodeprefix, docid, " +
203
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
204
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
205
          }
206 1217 tao
        // Increase DBConnection usage count
207
        connection.increaseUsageCount(1);
208 133 jones
      }
209 19 jones
210 133 jones
      // Bind the values to the query
211 758 bojilova
      pstmt.setString(1, nodetype);
212 826 bojilova
      int idx;
213
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
214
        pstmt.setString(2, nodename.substring(idx+1));
215
        pstmt.setString(3, nodename.substring(0,idx));
216
      } else {
217
        pstmt.setString(2, nodename);
218
        pstmt.setString(3, null);
219
      }
220
      pstmt.setString(4, docid);
221 5208 daigle
      if (nodetype != "DOCUMENT") {
222 133 jones
        if (nodetype == "ELEMENT") {
223 826 bojilova
          pstmt.setLong(5, getRootNodeID());
224
          pstmt.setLong(6, getParentID());
225
          pstmt.setString(7, data);
226
          pstmt.setInt(8, getNodeIndex());
227 133 jones
        } else {
228 826 bojilova
          pstmt.setLong(5, getRootNodeID());
229
          pstmt.setLong(6, getNodeID());
230
          pstmt.setString(7, data);
231
          pstmt.setInt(8, incChildNum());
232 72 bojilova
        }
233 133 jones
      }
234
      // Do the insertion
235 5208 daigle
      logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - SQL insert: " + pstmt.toString());
236 133 jones
      pstmt.execute();
237
      pstmt.close();
238 758 bojilova
239
      // get the generated unique id afterward
240 4335 daigle
      nid = DatabaseService.getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
241 5208 daigle
      //should increase connection usage!!!!!!
242 2358 sgarg
243
244 408 jones
      if (nodetype.equals("DOCUMENT")) {
245
        // Record the root node id that was generated from the database
246
        setRootNodeID(nid);
247
      }
248
249 177 jones
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
250 176 jones
251 177 jones
        // Record the node id that was generated from the database
252
        setNodeID(nid);
253 176 jones
254 177 jones
        // Record the node type that was passed to the method
255
        setNodeType(nodetype);
256
257
      }
258
259 5208 daigle
    } catch (SQLException sqle) {
260
      logMetacat.error("DBSAXNode.writeChildNodeToDBDataLimited - SQL error inserting node: " +
261
    		  "(" + nodetype + ", " + nodename + ", " + data + ") : " + sqle.getMessage());
262
      sqle.printStackTrace(System.err);
263
      throw new SAXException(sqle.getMessage());
264 110 bojilova
    }
265 1416 tao
    return nid;
266 133 jones
  }
267 110 bojilova
268 2358 sgarg
  /**
269 758 bojilova
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
270
   */
271
  public void updateRootNodeID(long nodeid) throws SAXException {
272
      try {
273
        PreparedStatement pstmt;
274 1217 tao
        pstmt = connection.prepareStatement(
275 758 bojilova
              "UPDATE xml_nodes set rootnodeid = ? " +
276
              "WHERE nodeid = ?");
277 1217 tao
        // Increase DBConnection usage count
278
        connection.increaseUsageCount(1);
279 758 bojilova
280
        // Bind the values to the query
281
        pstmt.setLong(1, nodeid);
282
        pstmt.setLong(2, nodeid);
283
        // Do the update
284
        pstmt.execute();
285
        pstmt.close();
286
      } catch (SQLException e) {
287 2358 sgarg
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
288 758 bojilova
                           e.getMessage());
289
        throw new SAXException(e.getMessage());
290
      }
291
  }
292
293 2358 sgarg
  /**
294
   * creates SQL code to put nodename for the document node
295
   * into DB connection
296 133 jones
   */
297 461 bojilova
  public void writeNodename(String nodename) throws SAXException {
298 133 jones
      try {
299
        PreparedStatement pstmt;
300 1217 tao
        pstmt = connection.prepareStatement(
301 133 jones
              "UPDATE xml_nodes set nodename = ? " +
302
              "WHERE nodeid = ?");
303 1217 tao
        // Increase DBConnection usage count
304
        connection.increaseUsageCount(1);
305 16 jones
306 133 jones
        // Bind the values to the query
307
        pstmt.setString(1, nodename);
308 134 jones
        pstmt.setLong(2, getNodeID());
309 133 jones
        // Do the insertion
310
        pstmt.execute();
311
        pstmt.close();
312
      } catch (SQLException e) {
313 2358 sgarg
        System.out.println("Error in DBSaxNode.writeNodeName: " +
314 675 berkley
                           e.getMessage());
315 461 bojilova
        throw new SAXException(e.getMessage());
316 133 jones
      }
317
  }
318 16 jones
319 1803 tao
 /** creates SQL code and inserts new node into DB connection */
320 2358 sgarg
  public long writeDTDNodeToDB(String nodename, String data, String docid)
321
                                 throws SAXException
322 1803 tao
  {
323
    long nid = -1;
324 2358 sgarg
    try
325 1803 tao
    {
326 2358 sgarg
327 1803 tao
      PreparedStatement pstmt;
328 5208 daigle
      logMetacat.info("DBSAXNode.writeDTDNodeToDB - Insert dtd into db: "+nodename +" "+data);
329 2358 sgarg
      if(data != null && !data.trim().equals("")){
330
            try{
331
                double numberData = Double.parseDouble(data);
332
                pstmt = connection.prepareStatement(
333
                    "INSERT INTO xml_nodes " +
334
                    "(nodetype, nodename, docid, " +
335
                    "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
336
                    "VALUES (?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
337
            } catch (NumberFormatException nfe) {
338
                pstmt = connection.prepareStatement(
339
                    "INSERT INTO xml_nodes " +
340
                    "(nodetype, nodename,  docid, " +
341
                    "rootnodeid, parentnodeid, nodedata, nodeindex) " +
342
                    "VALUES (?, ?, ?, ?, ?, ?, ?)");
343
            }
344
        } else {
345
            pstmt = connection.prepareStatement(
346
                  "INSERT INTO xml_nodes " +
347
                  "(nodetype, nodename, docid, " +
348
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
349
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
350
        }
351
352 1803 tao
       // Increase DBConnection usage count
353
      connection.increaseUsageCount(1);
354 2358 sgarg
355 1803 tao
      // Bind the values to the query
356
      pstmt.setString(1, DocumentImpl.DTD);
357
      pstmt.setString(2, nodename);
358
      pstmt.setString(3, docid);
359
      pstmt.setLong(4, getRootNodeID());
360
      pstmt.setLong(5, getParentID());
361
      pstmt.setString(6, data);
362
      pstmt.setInt(7, getNodeIndex());
363 2358 sgarg
364 1803 tao
      // Do the insertion
365
      pstmt.execute();
366
      pstmt.close();
367
368
      // get the generated unique id afterward
369 4335 daigle
      nid = DatabaseService.getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
370 1803 tao
      //should incease connection usage!!!!!!
371 2358 sgarg
372 1803 tao
    } catch (SQLException e) {
373
      System.out.println("Error in DBSaxNode.writeDTDNodeToDB");
374
      System.err.println("Error inserting node: (" + DocumentImpl.DTD + ", " +
375 2358 sgarg
                                                     nodename + ", " +
376 1803 tao
                                                     data + ")" );
377
      System.err.println(e.getMessage());
378
      e.printStackTrace(System.err);
379
      throw new SAXException(e.getMessage());
380
    }
381
    return nid;
382
  }
383 2358 sgarg
384
385 174 bojilova
  /** get next node id from DB connection */
386 461 bojilova
  private long generateNodeID() throws SAXException {
387 174 bojilova
      long nid=0;
388 133 jones
      Statement stmt;
389 1217 tao
      DBConnection dbConn = null;
390
      int serialNumber = -1;
391 133 jones
      try {
392 1217 tao
        // Get DBConnection
393
        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
394
        serialNumber=dbConn.getCheckOutSerialNumber();
395
        stmt = dbConn.createStatement();
396 174 bojilova
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
397 133 jones
        ResultSet rs = stmt.getResultSet();
398
        boolean tableHasRows = rs.next();
399
        if (tableHasRows) {
400 174 bojilova
          nid = rs.getLong(1);
401 19 jones
        }
402 133 jones
        stmt.close();
403
      } catch (SQLException e) {
404 2358 sgarg
        System.out.println("Error in DBSaxNode.generateNodeID: " +
405 675 berkley
                            e.getMessage());
406 461 bojilova
        throw new SAXException(e.getMessage());
407 15 jones
      }
408 1217 tao
      finally
409
      {
410
        // Return DBconnection
411
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
412
      }//finally
413 15 jones
414 174 bojilova
      return nid;
415 133 jones
  }
416 18 jones
417 137 jones
  /** Add a new attribute to this node, or set its value */
418 1416 tao
  public long setAttribute(String attName, String attValue, String docid)
419 2358 sgarg
              throws SAXException
420 1416 tao
  {
421
    long nodeId = -1;
422 2358 sgarg
    if (attName != null)
423 1416 tao
    {
424 133 jones
      // Enter the attribute in the hash table
425
      super.setAttribute(attName, attValue);
426 18 jones
427 133 jones
      // And enter the attribute in the database
428 1416 tao
      nodeId = writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
429 2358 sgarg
    }
430
    else
431 1416 tao
    {
432 133 jones
      System.err.println("Attribute name must not be null!");
433 461 bojilova
      throw new SAXException("Attribute name must not be null!");
434 18 jones
    }
435 1416 tao
    return nodeId;
436 133 jones
  }
437 176 jones
438 821 bojilova
  /** Add a namespace to this node */
439 1416 tao
  public long setNamespace(String prefix, String uri, String docid)
440 2358 sgarg
              throws SAXException
441 1416 tao
  {
442
    long nodeId = -1;
443 2358 sgarg
    if (prefix != null)
444 1416 tao
    {
445 821 bojilova
      // Enter the namespace in a hash table
446
      super.setNamespace(prefix, uri);
447
      // And enter the namespace in the database
448 1416 tao
      nodeId = writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
449 2358 sgarg
    }
450
    else
451 1416 tao
    {
452 821 bojilova
      System.err.println("Namespace prefix must not be null!");
453
      throw new SAXException("Namespace prefix must not be null!");
454
    }
455 1416 tao
    return nodeId;
456 821 bojilova
  }
457
458 176 jones
459 2358 sgarg
460
  /**
461 471 bojilova
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
462
   * Update the node index (xml_index) for this node by generating
463
   * test strings that represent all of the relative and absolute
464
   * paths through the XML tree from document root to this node
465
   */
466 2358 sgarg
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
467 471 bojilova
               throws SAXException
468
  {
469
    Hashtable pathlist = new Hashtable();
470
    boolean atStartingNode = true;
471
    boolean atRootDocumentNode = false;
472
    DBSAXNode nodePointer = this;
473
    StringBuffer currentPath = new StringBuffer();
474
    int counter = 0;
475
476
    // Create a Hashtable of all of the paths to reach this node
477
    // including absolute paths and relative paths
478
    while (!atRootDocumentNode) {
479
      if (atStartingNode) {
480
        currentPath.insert(0, nodePointer.getTagName());
481
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
482
        counter++;
483
        atStartingNode = false;
484
      } else {
485
        currentPath.insert(0, "/");
486
        currentPath.insert(0, nodePointer.getTagName());
487
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
488
        counter++;
489
      }
490
491
      // advance to the next parent node
492
      nodePointer = nodePointer.getParentNode();
493
494
      // If we're at the DOCUMENT node (root of DOM tree), add
495
      // the root "/" to make the absolute path
496
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
497
        currentPath.insert(0, "/");
498
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
499
        counter++;
500
        atRootDocumentNode = true;
501 2358 sgarg
      }
502 471 bojilova
    }
503
504
    try {
505
      // Create an insert statement to reuse for all of the path insertions
506
      PreparedStatement pstmt = conn.prepareStatement(
507 2358 sgarg
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " +
508
               "parentnodeid) " +
509 471 bojilova
              "VALUES (?, ?, ?, ?, ?)");
510 1217 tao
      // Increase usage count
511
      conn.increaseUsageCount(1);
512 2358 sgarg
513 471 bojilova
      pstmt.setString(3, docid);
514
      pstmt.setString(4, doctype);
515
      pstmt.setLong(5, getParentID());
516 2358 sgarg
517 471 bojilova
      // Step through the hashtable and insert each of the path values
518 176 jones
      Enumeration en = pathlist.keys();
519
      while (en.hasMoreElements()) {
520
        String path = (String)en.nextElement();
521
        Long nodeid = (Long)pathlist.get(path);
522
        pstmt.setLong(1, nodeid.longValue());
523
        pstmt.setString(2, path);
524 2358 sgarg
525 457 bojilova
        pstmt.executeUpdate();
526 176 jones
      }
527
      // Close the database statement
528
      pstmt.close();
529
    } catch (SQLException sqe) {
530 675 berkley
      System.err.println("SQL Exception while inserting path to index in " +
531 899 berkley
                         "DBSAXNode.updateNodeIndex for document " + docid);
532 176 jones
      System.err.println(sqe.getMessage());
533 461 bojilova
      throw new SAXException(sqe.getMessage());
534 176 jones
    }
535
  }
536 2358 sgarg
537 176 jones
  /** get the parent of this node */
538
  public DBSAXNode getParentNode() {
539
    return parentNode;
540
  }
541 15 jones
}