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
 *
8
 *   '$Author: daigle $'
9
 *     '$Date: 2008-12-09 14:56:50 -0800 (Tue, 09 Dec 2008) $'
10
 * '$Revision: 4661 $'
11
 *
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
 */
26

    
27
package edu.ucsb.nceas.metacat;
28

    
29
import java.sql.*;
30
import java.util.Hashtable;
31
import java.util.Enumeration;
32
import org.apache.log4j.Logger;
33
import org.xml.sax.SAXException;
34

    
35
import edu.ucsb.nceas.metacat.service.DatabaseService;
36

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

    
43
  private DBConnection	connection;
44
  private DBSAXNode	parentNode;
45
  private Logger logMetacat = Logger.getLogger(DBSAXNode.class);
46

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

    
54
    super();
55
    this.connection = conn;
56
    this.parentNode = null;
57
    writeChildNodeToDB("DOCUMENT", null, null, docid);
58
    updateRootNodeID(getNodeID());
59
  }
60

    
61
  /**
62
   * 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
  public DBSAXNode (DBConnection conn, String qName, String lName,
69
                    DBSAXNode parentNode, long rootnodeid,
70
                    String docid, String doctype)
71
                                               throws SAXException {
72

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

    
85
  /**
86
   * 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
  public DBSAXNode (DBConnection conn, String docName, String publicId,
95
                    String systemId, DBSAXNode parentNode, long rootnodeid,
96
                    String docid) throws SAXException
97
  {
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

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

    
135
      PreparedStatement pstmt;
136

    
137
      if (nodetype == "DOCUMENT") {
138
        pstmt = connection.prepareStatement(
139
            "INSERT INTO xml_nodes " +
140
            "(nodetype, nodename, nodeprefix, docid) " +
141
            "VALUES (?, ?, ?, ?)");
142

    
143
        // Increase DBConnection usage count
144
        connection.increaseUsageCount(1);
145
        logMetacat.info("INSERTING DOCNAME: " + nodename);
146
      } else {
147
          if(data != null && !data.trim().equals("")
148
             && !data.trim().equals("NaN") && !data.trim().equalsIgnoreCase("Infinity")){
149
              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
        // Increase DBConnection usage count
171
        connection.increaseUsageCount(1);
172
      }
173

    
174
      // Bind the values to the query
175
      pstmt.setString(1, nodetype);
176
      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
      if (nodetype == "DOCUMENT") {
186
        // moved it to separate method updateRootNodeID
187
        //pstmt.setLong(4, nid);
188
      } else {
189
        if (nodetype == "ELEMENT") {
190
          pstmt.setLong(5, getRootNodeID());
191
          pstmt.setLong(6, getParentID());
192
          pstmt.setString(7, data);
193
          pstmt.setInt(8, getNodeIndex());
194
        } else {
195
          pstmt.setLong(5, getRootNodeID());
196
          pstmt.setLong(6, getNodeID());
197
          pstmt.setString(7, data);
198
          pstmt.setInt(8, incChildNum());
199
        }
200
      }
201
      // Do the insertion
202
      logMetacat.debug("SQL insert: " + pstmt.toString());
203
      pstmt.execute();
204
      pstmt.close();
205

    
206
      // get the generated unique id afterward
207
      nid = DatabaseService.getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
208
      //should incease connection usage!!!!!!
209

    
210

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

    
216
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
217

    
218
        // Record the node id that was generated from the database
219
        setNodeID(nid);
220

    
221
        // Record the node type that was passed to the method
222
        setNodeType(nodetype);
223

    
224
      }
225

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

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

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

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

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

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

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

    
322
       // Increase DBConnection usage count
323
      connection.increaseUsageCount(1);
324

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

    
334
      // Do the insertion
335
      pstmt.execute();
336
      pstmt.close();
337

    
338
      // get the generated unique id afterward
339
      nid = DatabaseService.getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
340
      //should incease connection usage!!!!!!
341

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

    
354

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

    
384
      return nid;
385
  }
386

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

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

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

    
428

    
429

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

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

    
461
      // advance to the next parent node
462
      nodePointer = nodePointer.getParentNode();
463

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

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

    
483
      pstmt.setString(3, docid);
484
      pstmt.setString(4, doctype);
485
      pstmt.setLong(5, getParentID());
486

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

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

    
507
  /** get the parent of this node */
508
  public DBSAXNode getParentNode() {
509
    return parentNode;
510
  }
511
}
(23-23/69)