Project

General

Profile

1
/**
2
 *  '$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
 *    Release: @release@
8
 *
9
 *   '$Author: sgarg $'
10
 *     '$Date: 2005-10-10 11:06:55 -0700 (Mon, 10 Oct 2005) $'
11
 * '$Revision: 2663 $'
12
 *
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
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.sql.*;
31
import java.io.IOException;
32
import java.util.Hashtable;
33
import java.util.Enumeration;
34
//import oracle.jdbc.driver.*;
35
import org.apache.log4j.Logger;
36
import org.xml.sax.SAXException;
37

    
38
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
39

    
40
/**
41
 * A Class that represents an XML node and its contents and
42
 * can write its own representation to a database connection
43
 */
44
public class DBSAXNode extends BasicNode {
45

    
46
  private DBConnection	connection;
47
  private DBSAXNode	parentNode;
48
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
49
  private Logger logMetacat = Logger.getLogger(DBSAXNode.class);
50

    
51
  /**
52
   * Construct a new node instance for DOCUMENT nodes
53
   *
54
   * @param conn the JDBC Connection to which all information is written
55
   */
56
  public DBSAXNode (DBConnection conn, String docid) throws SAXException {
57

    
58
    super();
59
    this.connection = conn;
60
    this.parentNode = null;
61
    writeChildNodeToDB("DOCUMENT", null, null, docid);
62
    updateRootNodeID(getNodeID());
63
  }
64

    
65
  /**
66
   * Construct a new node instance for ELEMENT nodes
67
   *
68
   * @param conn the JDBC Connection to which all information is written
69
   * @param tagname the name of the node
70
   * @param parentNode the parent node for this node being created
71
   */
72
  public DBSAXNode (DBConnection conn, String qName, String lName,
73
                    DBSAXNode parentNode, long rootnodeid,
74
                    String docid, String doctype)
75
                                               throws SAXException {
76

    
77
    super(lName);
78
    this.connection = conn;
79
    this.parentNode = parentNode;
80
    setParentID(parentNode.getNodeID());
81
    setRootNodeID(rootnodeid);
82
    setDocID(docid);
83
    setNodeIndex(parentNode.incChildNum());
84
    writeChildNodeToDB("ELEMENT", qName, null, docid);
85
    //No writing XML Index from here. New Thread used instead.
86
    //updateNodeIndex(docid, doctype);
87
  }
88

    
89
  /**
90
   * Construct a new node instance for DTD nodes
91
   * This Node will write docname, publicId and systemId into db. Only
92
   * handle systemid  existed.(external dtd)
93
   *
94
   * @param conn the JDBC Connection to which all information is written
95
   * @param tagname the name of the node
96
   * @param parentNode the parent node for this node being created
97
   */
98
  public DBSAXNode (DBConnection conn, String docName, String publicId,
99
                    String systemId, DBSAXNode parentNode, long rootnodeid,
100
                    String docid) throws SAXException
101
  {
102

    
103
    super();
104
    this.connection = conn;
105
    this.parentNode = parentNode;
106
    setParentID(parentNode.getNodeID());
107
    setRootNodeID(rootnodeid);
108
    setDocID(docid);
109
    // insert dtd node only for external dtd definiation
110
    if (systemId != null)
111
    {
112
      //write docname to DB
113
      if (docName != null)
114
      {
115
        setNodeIndex(parentNode.incChildNum());
116
        writeDTDNodeToDB(DocumentImpl.DOCNAME, docName, docid);
117
      }
118
      //write publicId to DB
119
      if (publicId != null)
120
      {
121
        setNodeIndex(parentNode.incChildNum());
122
        writeDTDNodeToDB(DocumentImpl.PUBLICID, publicId, docid);
123
      }
124
      //write systemId to DB
125
      setNodeIndex(parentNode.incChildNum());
126
      writeDTDNodeToDB(DocumentImpl.SYSTEMID, systemId, docid);
127
    }
128
  }
129

    
130
  /** creates SQL code and inserts new node into DB connection */
131
  public long writeChildNodeToDB(String nodetype, String nodename,
132
                                 String data, String docid)
133
                                 throws SAXException
134
  {
135
    long nid = -1;
136
    try
137
    {
138

    
139
      PreparedStatement pstmt;
140

    
141
      if (nodetype == "DOCUMENT") {
142
        pstmt = connection.prepareStatement(
143
            "INSERT INTO xml_nodes " +
144
            "(nodetype, nodename, nodeprefix, docid) " +
145
            "VALUES (?, ?, ?, ?)");
146

    
147
        // Increase DBConnection usage count
148
        connection.increaseUsageCount(1);
149
        logMetacat.info("INSERTING DOCNAME: " + nodename);
150
      } else {
151
          if(data != null && !data.trim().equals("")
152
             && !data.trim().equals("NaN")){
153
              try{
154
                  double numberData = Double.parseDouble(data);
155
                  pstmt = connection.prepareStatement(
156
                      "INSERT INTO xml_nodes " +
157
                      "(nodetype, nodename, nodeprefix, docid, " +
158
                      "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
159
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
160
              } catch (NumberFormatException nfe) {
161
                  pstmt = connection.prepareStatement(
162
                      "INSERT INTO xml_nodes " +
163
                      "(nodetype, nodename, nodeprefix, docid, " +
164
                      "rootnodeid, parentnodeid, nodedata, nodeindex) " +
165
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
166
              }
167
          } else {
168
              pstmt = connection.prepareStatement(
169
                  "INSERT INTO xml_nodes " +
170
                  "(nodetype, nodename, nodeprefix, docid, " +
171
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
172
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
173
          }
174
        // Increase DBConnection usage count
175
        connection.increaseUsageCount(1);
176
      }
177

    
178
      // Bind the values to the query
179
      pstmt.setString(1, nodetype);
180
      int idx;
181
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
182
        pstmt.setString(2, nodename.substring(idx+1));
183
        pstmt.setString(3, nodename.substring(0,idx));
184
      } else {
185
        pstmt.setString(2, nodename);
186
        pstmt.setString(3, null);
187
      }
188
      pstmt.setString(4, docid);
189
      if (nodetype == "DOCUMENT") {
190
        // moved it to separate method updateRootNodeID
191
        //pstmt.setLong(4, nid);
192
      } else {
193
        if (nodetype == "ELEMENT") {
194
          pstmt.setLong(5, getRootNodeID());
195
          pstmt.setLong(6, getParentID());
196
          pstmt.setString(7, data);
197
          pstmt.setInt(8, getNodeIndex());
198
        } else {
199
          pstmt.setLong(5, getRootNodeID());
200
          pstmt.setLong(6, getNodeID());
201
          pstmt.setString(7, data);
202
          pstmt.setInt(8, incChildNum());
203
        }
204
      }
205
      // Do the insertion
206
      pstmt.execute();
207
      pstmt.close();
208

    
209
      // get the generated unique id afterward
210
      nid = dbAdapter.getUniqueID(connection.getConnections(), "xml_nodes");
211
      //should incease connection usage!!!!!!
212

    
213

    
214
      if (nodetype.equals("DOCUMENT")) {
215
        // Record the root node id that was generated from the database
216
        setRootNodeID(nid);
217
      }
218

    
219
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
220

    
221
        // Record the node id that was generated from the database
222
        setNodeID(nid);
223

    
224
        // Record the node type that was passed to the method
225
        setNodeType(nodetype);
226

    
227
      }
228

    
229
    } catch (SQLException e) {
230
      System.out.println("Error in DBSaxNode.writeChildNodeToDB");
231
      System.err.println("Error inserting node: (" + nodetype + ", " +
232
                                                     nodename + ", " +
233
                                                     data + ")" );
234
      System.err.println(e.getMessage());
235
      e.printStackTrace(System.err);
236
      throw new SAXException(e.getMessage());
237
    }
238
    return nid;
239
  }
240

    
241
  /**
242
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
243
   */
244
  public void updateRootNodeID(long nodeid) throws SAXException {
245
      try {
246
        PreparedStatement pstmt;
247
        pstmt = connection.prepareStatement(
248
              "UPDATE xml_nodes set rootnodeid = ? " +
249
              "WHERE nodeid = ?");
250
        // Increase DBConnection usage count
251
        connection.increaseUsageCount(1);
252

    
253
        // Bind the values to the query
254
        pstmt.setLong(1, nodeid);
255
        pstmt.setLong(2, nodeid);
256
        // Do the update
257
        pstmt.execute();
258
        pstmt.close();
259
      } catch (SQLException e) {
260
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
261
                           e.getMessage());
262
        throw new SAXException(e.getMessage());
263
      }
264
  }
265

    
266
  /**
267
   * creates SQL code to put nodename for the document node
268
   * into DB connection
269
   */
270
  public void writeNodename(String nodename) throws SAXException {
271
      try {
272
        PreparedStatement pstmt;
273
        pstmt = connection.prepareStatement(
274
              "UPDATE xml_nodes set nodename = ? " +
275
              "WHERE nodeid = ?");
276
        // Increase DBConnection usage count
277
        connection.increaseUsageCount(1);
278

    
279
        // Bind the values to the query
280
        pstmt.setString(1, nodename);
281
        pstmt.setLong(2, getNodeID());
282
        // Do the insertion
283
        pstmt.execute();
284
        pstmt.close();
285
      } catch (SQLException e) {
286
        System.out.println("Error in DBSaxNode.writeNodeName: " +
287
                           e.getMessage());
288
        throw new SAXException(e.getMessage());
289
      }
290
  }
291

    
292
 /** creates SQL code and inserts new node into DB connection */
293
  public long writeDTDNodeToDB(String nodename, String data, String docid)
294
                                 throws SAXException
295
  {
296
    long nid = -1;
297
    try
298
    {
299

    
300
      PreparedStatement pstmt;
301
      logMetacat.info("Insert dtd into db: "+nodename +" "+data);
302
      if(data != null && !data.trim().equals("")){
303
            try{
304
                double numberData = Double.parseDouble(data);
305
                pstmt = connection.prepareStatement(
306
                    "INSERT INTO xml_nodes " +
307
                    "(nodetype, nodename, docid, " +
308
                    "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
309
                    "VALUES (?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
310
            } catch (NumberFormatException nfe) {
311
                pstmt = connection.prepareStatement(
312
                    "INSERT INTO xml_nodes " +
313
                    "(nodetype, nodename,  docid, " +
314
                    "rootnodeid, parentnodeid, nodedata, nodeindex) " +
315
                    "VALUES (?, ?, ?, ?, ?, ?, ?)");
316
            }
317
        } else {
318
            pstmt = connection.prepareStatement(
319
                  "INSERT INTO xml_nodes " +
320
                  "(nodetype, nodename, docid, " +
321
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
322
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
323
        }
324

    
325
       // Increase DBConnection usage count
326
      connection.increaseUsageCount(1);
327

    
328
      // Bind the values to the query
329
      pstmt.setString(1, DocumentImpl.DTD);
330
      pstmt.setString(2, nodename);
331
      pstmt.setString(3, docid);
332
      pstmt.setLong(4, getRootNodeID());
333
      pstmt.setLong(5, getParentID());
334
      pstmt.setString(6, data);
335
      pstmt.setInt(7, getNodeIndex());
336

    
337
      // Do the insertion
338
      pstmt.execute();
339
      pstmt.close();
340

    
341
      // get the generated unique id afterward
342
      nid = dbAdapter.getUniqueID(connection.getConnections(), "xml_nodes");
343
      //should incease connection usage!!!!!!
344

    
345
    } catch (SQLException e) {
346
      System.out.println("Error in DBSaxNode.writeDTDNodeToDB");
347
      System.err.println("Error inserting node: (" + DocumentImpl.DTD + ", " +
348
                                                     nodename + ", " +
349
                                                     data + ")" );
350
      System.err.println(e.getMessage());
351
      e.printStackTrace(System.err);
352
      throw new SAXException(e.getMessage());
353
    }
354
    return nid;
355
  }
356

    
357

    
358
  /** get next node id from DB connection */
359
  private long generateNodeID() throws SAXException {
360
      long nid=0;
361
      Statement stmt;
362
      DBConnection dbConn = null;
363
      int serialNumber = -1;
364
      try {
365
        // Get DBConnection
366
        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
367
        serialNumber=dbConn.getCheckOutSerialNumber();
368
        stmt = dbConn.createStatement();
369
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
370
        ResultSet rs = stmt.getResultSet();
371
        boolean tableHasRows = rs.next();
372
        if (tableHasRows) {
373
          nid = rs.getLong(1);
374
        }
375
        stmt.close();
376
      } catch (SQLException e) {
377
        System.out.println("Error in DBSaxNode.generateNodeID: " +
378
                            e.getMessage());
379
        throw new SAXException(e.getMessage());
380
      }
381
      finally
382
      {
383
        // Return DBconnection
384
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
385
      }//finally
386

    
387
      return nid;
388
  }
389

    
390
  /** Add a new attribute to this node, or set its value */
391
  public long setAttribute(String attName, String attValue, String docid)
392
              throws SAXException
393
  {
394
    long nodeId = -1;
395
    if (attName != null)
396
    {
397
      // Enter the attribute in the hash table
398
      super.setAttribute(attName, attValue);
399

    
400
      // And enter the attribute in the database
401
      nodeId = writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
402
    }
403
    else
404
    {
405
      System.err.println("Attribute name must not be null!");
406
      throw new SAXException("Attribute name must not be null!");
407
    }
408
    return nodeId;
409
  }
410

    
411
  /** Add a namespace to this node */
412
  public long setNamespace(String prefix, String uri, String docid)
413
              throws SAXException
414
  {
415
    long nodeId = -1;
416
    if (prefix != null)
417
    {
418
      // Enter the namespace in a hash table
419
      super.setNamespace(prefix, uri);
420
      // And enter the namespace in the database
421
      nodeId = writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
422
    }
423
    else
424
    {
425
      System.err.println("Namespace prefix must not be null!");
426
      throw new SAXException("Namespace prefix must not be null!");
427
    }
428
    return nodeId;
429
  }
430

    
431

    
432

    
433
  /**
434
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
435
   * Update the node index (xml_index) for this node by generating
436
   * test strings that represent all of the relative and absolute
437
   * paths through the XML tree from document root to this node
438
   */
439
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
440
               throws SAXException
441
  {
442
    Hashtable pathlist = new Hashtable();
443
    boolean atStartingNode = true;
444
    boolean atRootDocumentNode = false;
445
    DBSAXNode nodePointer = this;
446
    StringBuffer currentPath = new StringBuffer();
447
    int counter = 0;
448

    
449
    // Create a Hashtable of all of the paths to reach this node
450
    // including absolute paths and relative paths
451
    while (!atRootDocumentNode) {
452
      if (atStartingNode) {
453
        currentPath.insert(0, nodePointer.getTagName());
454
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
455
        counter++;
456
        atStartingNode = false;
457
      } else {
458
        currentPath.insert(0, "/");
459
        currentPath.insert(0, nodePointer.getTagName());
460
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
461
        counter++;
462
      }
463

    
464
      // advance to the next parent node
465
      nodePointer = nodePointer.getParentNode();
466

    
467
      // If we're at the DOCUMENT node (root of DOM tree), add
468
      // the root "/" to make the absolute path
469
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
470
        currentPath.insert(0, "/");
471
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
472
        counter++;
473
        atRootDocumentNode = true;
474
      }
475
    }
476

    
477
    try {
478
      // Create an insert statement to reuse for all of the path insertions
479
      PreparedStatement pstmt = conn.prepareStatement(
480
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " +
481
               "parentnodeid) " +
482
              "VALUES (?, ?, ?, ?, ?)");
483
      // Increase usage count
484
      conn.increaseUsageCount(1);
485

    
486
      pstmt.setString(3, docid);
487
      pstmt.setString(4, doctype);
488
      pstmt.setLong(5, getParentID());
489

    
490
      // Step through the hashtable and insert each of the path values
491
      Enumeration en = pathlist.keys();
492
      while (en.hasMoreElements()) {
493
        String path = (String)en.nextElement();
494
        Long nodeid = (Long)pathlist.get(path);
495
        pstmt.setLong(1, nodeid.longValue());
496
        pstmt.setString(2, path);
497

    
498
        pstmt.executeUpdate();
499
      }
500
      // Close the database statement
501
      pstmt.close();
502
    } catch (SQLException sqe) {
503
      System.err.println("SQL Exception while inserting path to index in " +
504
                         "DBSAXNode.updateNodeIndex for document " + docid);
505
      System.err.println(sqe.getMessage());
506
      throw new SAXException(sqe.getMessage());
507
    }
508
  }
509

    
510
  /** get the parent of this node */
511
  public DBSAXNode getParentNode() {
512
    return parentNode;
513
  }
514
}
(24-24/65)