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: leinfelder $'
9
 *     '$Date: 2011-03-24 15:10:15 -0700 (Thu, 24 Mar 2011) $'
10
 * '$Revision: 6020 $'
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.PreparedStatement;
30
import java.sql.ResultSet;
31
import java.sql.SQLException;
32
import java.sql.Statement;
33
import java.util.Enumeration;
34
import java.util.Hashtable;
35

    
36
import org.apache.log4j.Logger;
37
import org.xml.sax.SAXException;
38

    
39
import edu.ucsb.nceas.metacat.database.DBConnection;
40
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
41
import edu.ucsb.nceas.metacat.database.DatabaseService;
42

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

    
49
  private DBConnection	connection;
50
  private DBSAXNode	parentNode;
51
  private Logger logMetacat = Logger.getLogger(DBSAXNode.class);
52

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

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

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

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

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

    
105
    super();
106
    this.connection = conn;
107
    this.parentNode = parentNode;
108
    setParentID(parentNode.getNodeID());
109
    setRootNodeID(rootnodeid);
110
    setDocID(docid);
111
    // insert dtd node only for external dtd definiation
112
    if (systemId != null)
113
    {
114
      //write docname to DB
115
      if (docName != null)
116
      {
117
        setNodeIndex(parentNode.incChildNum());
118
        writeDTDNodeToDB(DocumentImpl.DOCNAME, docName, docid);
119
      }
120
      //write publicId to DB
121
      if (publicId != null)
122
      {
123
        setNodeIndex(parentNode.incChildNum());
124
        writeDTDNodeToDB(DocumentImpl.PUBLICID, publicId, docid);
125
      }
126
      //write systemId to DB
127
      setNodeIndex(parentNode.incChildNum());
128
      writeDTDNodeToDB(DocumentImpl.SYSTEMID, systemId, docid);
129
    }
130
  }
131
  
132
  /** creates SQL code and inserts new node into DB connection */
133
  public long writeChildNodeToDB(String nodetype, String nodename,
134
                                 String data, String docid)
135
                                 throws SAXException {
136
    String limitedData = null;
137
    int leftover = 0;
138
    if (data != null) {
139
    	leftover = data.length();
140
    }
141
    int offset = 0;
142
    boolean moredata = true;
143
    long endNodeId = -1;
144

    
145
    // This loop deals with the case where there are more characters
146
    // than can fit in a single database text field (limit is
147
    // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
148
    // write a series of nodes that are MAXDATACHARS long, and then the
149
    // final node contains the remainder
150
    while (moredata) {
151
        if (leftover > (DBSAXHandler.MAXDATACHARS)) {
152
        	limitedData = data.substring(offset, DBSAXHandler.MAXDATACHARS);
153
            leftover -= (DBSAXHandler.MAXDATACHARS - 1);
154
            offset += (DBSAXHandler.MAXDATACHARS - 1);
155
        } else {
156
        	if (data != null) {
157
        		limitedData = data.substring(offset, offset + leftover);
158
        	} else {
159
        		limitedData = null;
160
        	}
161
        	moredata = false;
162
        }
163
        
164
        endNodeId =  writeChildNodeToDBDataLimited(nodetype, nodename, limitedData, docid);
165
    }
166
    
167
    return endNodeId;
168
  }
169

    
170
  /** creates SQL code and inserts new node into DB connection */
171
  public long writeChildNodeToDBDataLimited(String nodetype, String nodename,
172
                                 String data, String docid)
173
                                 throws SAXException
174
  {
175
    long nid = -1;
176
    try
177
    {
178

    
179
      PreparedStatement pstmt;
180
      
181
      if (nodetype == "DOCUMENT") {
182
        pstmt = connection.prepareStatement(
183
            "INSERT INTO xml_nodes " +
184
            "(nodetype, nodename, nodeprefix, docid) " +
185
            "VALUES (?, ?, ?, ?)");
186

    
187
        logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - inserting doc name: " + nodename);
188
      } else {
189
          pstmt = connection.prepareStatement(
190
              "INSERT INTO xml_nodes " +
191
              "(nodetype, nodename, nodeprefix, docid, " +
192
              "rootnodeid, parentnodeid, nodedata, nodeindex) " +
193
              "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
194
      }
195
      
196
      // Increase DBConnection usage count
197
      connection.increaseUsageCount(1);
198
      
199
      // Bind the values to the query
200
      pstmt.setString(1, nodetype);
201
      int idx;
202
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
203
        pstmt.setString(2, nodename.substring(idx+1));
204
        pstmt.setString(3, nodename.substring(0,idx));
205
      } else {
206
        pstmt.setString(2, nodename);
207
        pstmt.setString(3, null);
208
      }
209
      pstmt.setString(4, docid);
210
      if (nodetype != "DOCUMENT") {
211
        if (nodetype == "ELEMENT") {
212
          pstmt.setLong(5, getRootNodeID());
213
          pstmt.setLong(6, getParentID());
214
          pstmt.setString(7, data);
215
          pstmt.setInt(8, getNodeIndex());
216
        } else {
217
          pstmt.setLong(5, getRootNodeID());
218
          pstmt.setLong(6, getNodeID());
219
          pstmt.setString(7, data);
220
          pstmt.setInt(8, incChildNum());
221
        }
222
      }
223
      // Do the insertion
224
      logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - SQL insert: " + pstmt.toString());
225
      pstmt.execute();
226
      pstmt.close();
227

    
228
      // get the generated unique id afterward
229
      nid = DatabaseService.getInstance().getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
230
      //should increase connection usage!!!!!!
231

    
232
      if (nodetype.equals("DOCUMENT")) {
233
        // Record the root node id that was generated from the database
234
        setRootNodeID(nid);
235
      }
236

    
237
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
238

    
239
        // Record the node id that was generated from the database
240
        setNodeID(nid);
241

    
242
        // Record the node type that was passed to the method
243
        setNodeType(nodetype);
244

    
245
      }
246

    
247
    } catch (SQLException sqle) {
248
      logMetacat.error("DBSAXNode.writeChildNodeToDBDataLimited - SQL error inserting node: " + 
249
    		  "(" + nodetype + ", " + nodename + ", " + data + ") : " + sqle.getMessage());
250
      sqle.printStackTrace(System.err);
251
      throw new SAXException(sqle.getMessage());
252
    }
253
    return nid;
254
  }
255

    
256
  /**
257
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
258
   */
259
  public void updateRootNodeID(long nodeid) throws SAXException {
260
      try {
261
        PreparedStatement pstmt;
262
        pstmt = connection.prepareStatement(
263
              "UPDATE xml_nodes set rootnodeid = ? " +
264
              "WHERE nodeid = ?");
265
        // Increase DBConnection usage count
266
        connection.increaseUsageCount(1);
267

    
268
        // Bind the values to the query
269
        pstmt.setLong(1, nodeid);
270
        pstmt.setLong(2, nodeid);
271
        // Do the update
272
        pstmt.execute();
273
        pstmt.close();
274
      } catch (SQLException e) {
275
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
276
                           e.getMessage());
277
        throw new SAXException(e.getMessage());
278
      }
279
  }
280

    
281
  /**
282
   * creates SQL code to put nodename for the document node
283
   * into DB connection
284
   */
285
  public void writeNodename(String nodename) throws SAXException {
286
      try {
287
        PreparedStatement pstmt;
288
        pstmt = connection.prepareStatement(
289
              "UPDATE xml_nodes set nodename = ? " +
290
              "WHERE nodeid = ?");
291
        // Increase DBConnection usage count
292
        connection.increaseUsageCount(1);
293

    
294
        // Bind the values to the query
295
        pstmt.setString(1, nodename);
296
        pstmt.setLong(2, getNodeID());
297
        // Do the insertion
298
        pstmt.execute();
299
        pstmt.close();
300
      } catch (SQLException e) {
301
        System.out.println("Error in DBSaxNode.writeNodeName: " +
302
                           e.getMessage());
303
        throw new SAXException(e.getMessage());
304
      }
305
  }
306

    
307
 /** creates SQL code and inserts new node into DB connection */
308
  public long writeDTDNodeToDB(String nodename, String data, String docid)
309
                                 throws SAXException
310
  {
311
    long nid = -1;
312
    try
313
    {
314

    
315
      PreparedStatement pstmt;
316
      logMetacat.info("DBSAXNode.writeDTDNodeToDB - Insert dtd into db: "+nodename +" "+data);
317
  
318
      pstmt = connection.prepareStatement(
319
              "INSERT INTO xml_nodes " +
320
              "(nodetype, nodename, docid, " +
321
              "rootnodeid, parentnodeid, nodedata, nodeindex) " +
322
              "VALUES (?, ?, ?, ?, ?, ?, ?)");
323

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

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

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

    
340
      // get the generated unique id afterward
341
      nid = DatabaseService.getInstance().getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
342

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

    
355

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

    
385
      return nid;
386
  }
387

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

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

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

    
429

    
430

    
431
  /**
432
   * 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
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
438
               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
      }
473
    }
474

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

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

    
488
      // Step through the hashtable and insert each of the path values
489
      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

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

    
508
  /** get the parent of this node */
509
  public DBSAXNode getParentNode() {
510
    return parentNode;
511
  }
512
}
(19-19/65)