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