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-16 22:56:31 -0700 (Wed, 16 Mar 2011) $'
10
 * '$Revision: 6012 $'
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.text.ParseException;
31
import java.text.SimpleDateFormat;
32
import java.util.Date;
33
import java.util.Hashtable;
34
import java.util.Enumeration;
35
import org.apache.log4j.Logger;
36
import org.xml.sax.SAXException;
37

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

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

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

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

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

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

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

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

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

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

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

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

    
187
        // Increase DBConnection usage count
188
        connection.increaseUsageCount(1);
189
        logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - inserting doc name: " + nodename);
190
      } else {
191
          if(data != null && !data.trim().equals("")
192
             && !data.trim().equals("NaN") && !data.trim().equalsIgnoreCase("Infinity")){
193
        	  try{
194
        		  // try some common ISO 8601 formats
195
        		  SimpleDateFormat sdf = null;
196
        		  if (data.length() == 10) {
197
        			  sdf = new SimpleDateFormat("yyyy-MM-dd");
198
        		  } else if (data.length() == 19) {
199
        			  sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
200
        		  } else {
201
        			  // throw this so we continue with parsing as numeric or string.
202
        			  throw new ParseException("String length will not match date/dateTime patterns", -1);
203
        		  }
204
        		  Date dateData = sdf.parse(data);
205
        		  timestampData = new Timestamp(dateData.getTime());
206
                  pstmt = connection.prepareStatement(
207
                      "INSERT INTO xml_nodes " +
208
                      "(nodetype, nodename, nodeprefix, docid, " +
209
                      "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatadate) " +
210
                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
211
              } catch (ParseException pe) {
212
	        	  try{
213
	                  double numberData = Double.parseDouble(data);
214
	                  pstmt = connection.prepareStatement(
215
	                      "INSERT INTO xml_nodes " +
216
	                      "(nodetype, nodename, nodeprefix, docid, " +
217
	                      "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
218
	                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
219
	              } catch (NumberFormatException nfe) {
220
	                  pstmt = connection.prepareStatement(
221
	                      "INSERT INTO xml_nodes " +
222
	                      "(nodetype, nodename, nodeprefix, docid, " +
223
	                      "rootnodeid, parentnodeid, nodedata, nodeindex) " +
224
	                      "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
225
	              }
226
              }
227
          } else {
228
              pstmt = connection.prepareStatement(
229
                  "INSERT INTO xml_nodes " +
230
                  "(nodetype, nodename, nodeprefix, docid, " +
231
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
232
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
233
          }
234
        // Increase DBConnection usage count
235
        connection.increaseUsageCount(1);
236
      }
237

    
238
      // Bind the values to the query
239
      pstmt.setString(1, nodetype);
240
      int idx;
241
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
242
        pstmt.setString(2, nodename.substring(idx+1));
243
        pstmt.setString(3, nodename.substring(0,idx));
244
      } else {
245
        pstmt.setString(2, nodename);
246
        pstmt.setString(3, null);
247
      }
248
      pstmt.setString(4, docid);
249
      if (nodetype != "DOCUMENT") {
250
        if (nodetype == "ELEMENT") {
251
          pstmt.setLong(5, getRootNodeID());
252
          pstmt.setLong(6, getParentID());
253
          pstmt.setString(7, data);
254
          pstmt.setInt(8, getNodeIndex());
255
        } else {
256
          pstmt.setLong(5, getRootNodeID());
257
          pstmt.setLong(6, getNodeID());
258
          pstmt.setString(7, data);
259
          pstmt.setInt(8, incChildNum());
260
        }
261
      }
262
      if (timestampData != null) {
263
    	  pstmt.setTimestamp(9, timestampData);
264
      }
265
      // Do the insertion
266
      logMetacat.debug("DBSAXNode.writeChildNodeToDBDataLimited - SQL insert: " + pstmt.toString());
267
      pstmt.execute();
268
      pstmt.close();
269

    
270
      // get the generated unique id afterward
271
      nid = DatabaseService.getInstance().getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
272
      //should increase connection usage!!!!!!
273

    
274

    
275
      if (nodetype.equals("DOCUMENT")) {
276
        // Record the root node id that was generated from the database
277
        setRootNodeID(nid);
278
      }
279

    
280
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
281

    
282
        // Record the node id that was generated from the database
283
        setNodeID(nid);
284

    
285
        // Record the node type that was passed to the method
286
        setNodeType(nodetype);
287

    
288
      }
289

    
290
    } catch (SQLException sqle) {
291
      logMetacat.error("DBSAXNode.writeChildNodeToDBDataLimited - SQL error inserting node: " + 
292
    		  "(" + nodetype + ", " + nodename + ", " + data + ") : " + sqle.getMessage());
293
      sqle.printStackTrace(System.err);
294
      throw new SAXException(sqle.getMessage());
295
    }
296
    return nid;
297
  }
298

    
299
  /**
300
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
301
   */
302
  public void updateRootNodeID(long nodeid) throws SAXException {
303
      try {
304
        PreparedStatement pstmt;
305
        pstmt = connection.prepareStatement(
306
              "UPDATE xml_nodes set rootnodeid = ? " +
307
              "WHERE nodeid = ?");
308
        // Increase DBConnection usage count
309
        connection.increaseUsageCount(1);
310

    
311
        // Bind the values to the query
312
        pstmt.setLong(1, nodeid);
313
        pstmt.setLong(2, nodeid);
314
        // Do the update
315
        pstmt.execute();
316
        pstmt.close();
317
      } catch (SQLException e) {
318
        System.out.println("Error in DBSaxNode.updateRootNodeID: " +
319
                           e.getMessage());
320
        throw new SAXException(e.getMessage());
321
      }
322
  }
323

    
324
  /**
325
   * creates SQL code to put nodename for the document node
326
   * into DB connection
327
   */
328
  public void writeNodename(String nodename) throws SAXException {
329
      try {
330
        PreparedStatement pstmt;
331
        pstmt = connection.prepareStatement(
332
              "UPDATE xml_nodes set nodename = ? " +
333
              "WHERE nodeid = ?");
334
        // Increase DBConnection usage count
335
        connection.increaseUsageCount(1);
336

    
337
        // Bind the values to the query
338
        pstmt.setString(1, nodename);
339
        pstmt.setLong(2, getNodeID());
340
        // Do the insertion
341
        pstmt.execute();
342
        pstmt.close();
343
      } catch (SQLException e) {
344
        System.out.println("Error in DBSaxNode.writeNodeName: " +
345
                           e.getMessage());
346
        throw new SAXException(e.getMessage());
347
      }
348
  }
349

    
350
 /** creates SQL code and inserts new node into DB connection */
351
  public long writeDTDNodeToDB(String nodename, String data, String docid)
352
                                 throws SAXException
353
  {
354
    long nid = -1;
355
    try
356
    {
357

    
358
      PreparedStatement pstmt;
359
      Timestamp timestampData = null;
360
      logMetacat.info("DBSAXNode.writeDTDNodeToDB - Insert dtd into db: "+nodename +" "+data);
361
      if(data != null && !data.trim().equals("")){
362
    	  try{
363
    		  // try some common ISO 8601 formats
364
    		  SimpleDateFormat sdf = null;
365
    		  if (data.length() == 10) {
366
    			  sdf = new SimpleDateFormat("yyyy-MM-dd");
367
    		  } else if (data.length() == 19) {
368
    			  sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
369
    		  }
370
    		  Date dateData = sdf.parse(data);
371
    		  timestampData = new Timestamp(dateData.getTime());
372
              pstmt = connection.prepareStatement(
373
                  "INSERT INTO xml_nodes " +
374
                  "(nodetype, nodename, docid, " +
375
                  "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatadate) " +
376
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
377
          } catch (ParseException pe) {
378
    	  	try{
379
                double numberData = Double.parseDouble(data);
380
                pstmt = connection.prepareStatement(
381
                    "INSERT INTO xml_nodes " +
382
                    "(nodetype, nodename, docid, " +
383
                    "rootnodeid, parentnodeid, nodedata, nodeindex, nodedatanumerical) " +
384
                    "VALUES (?, ?, ?, ?, ?, ?, ?, "+ numberData +")");
385
            } catch (NumberFormatException nfe) {
386
                pstmt = connection.prepareStatement(
387
                    "INSERT INTO xml_nodes " +
388
                    "(nodetype, nodename,  docid, " +
389
                    "rootnodeid, parentnodeid, nodedata, nodeindex) " +
390
                    "VALUES (?, ?, ?, ?, ?, ?, ?)");
391
            }
392
          }
393
        } else {
394
            pstmt = connection.prepareStatement(
395
                  "INSERT INTO xml_nodes " +
396
                  "(nodetype, nodename, docid, " +
397
                  "rootnodeid, parentnodeid, nodedata, nodeindex) " +
398
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
399
        }
400

    
401
       // Increase DBConnection usage count
402
      connection.increaseUsageCount(1);
403

    
404
      // Bind the values to the query
405
      pstmt.setString(1, DocumentImpl.DTD);
406
      pstmt.setString(2, nodename);
407
      pstmt.setString(3, docid);
408
      pstmt.setLong(4, getRootNodeID());
409
      pstmt.setLong(5, getParentID());
410
      pstmt.setString(6, data);
411
      pstmt.setInt(7, getNodeIndex());
412
      if (timestampData != null) {
413
    	  pstmt.setTimestamp(8, timestampData);
414
      }
415

    
416
      // Do the insertion
417
      pstmt.execute();
418
      pstmt.close();
419

    
420
      // get the generated unique id afterward
421
      nid = DatabaseService.getInstance().getDBAdapter().getUniqueID(connection.getConnections(), "xml_nodes");
422
      //should incease connection usage!!!!!!
423

    
424
    } catch (SQLException e) {
425
      System.out.println("Error in DBSaxNode.writeDTDNodeToDB");
426
      System.err.println("Error inserting node: (" + DocumentImpl.DTD + ", " +
427
                                                     nodename + ", " +
428
                                                     data + ")" );
429
      System.err.println(e.getMessage());
430
      e.printStackTrace(System.err);
431
      throw new SAXException(e.getMessage());
432
    }
433
    return nid;
434
  }
435

    
436

    
437
  /** get next node id from DB connection */
438
  private long generateNodeID() throws SAXException {
439
      long nid=0;
440
      Statement stmt;
441
      DBConnection dbConn = null;
442
      int serialNumber = -1;
443
      try {
444
        // Get DBConnection
445
        dbConn=DBConnectionPool.getDBConnection("DBSAXNode.generateNodeID");
446
        serialNumber=dbConn.getCheckOutSerialNumber();
447
        stmt = dbConn.createStatement();
448
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
449
        ResultSet rs = stmt.getResultSet();
450
        boolean tableHasRows = rs.next();
451
        if (tableHasRows) {
452
          nid = rs.getLong(1);
453
        }
454
        stmt.close();
455
      } catch (SQLException e) {
456
        System.out.println("Error in DBSaxNode.generateNodeID: " +
457
                            e.getMessage());
458
        throw new SAXException(e.getMessage());
459
      }
460
      finally
461
      {
462
        // Return DBconnection
463
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
464
      }//finally
465

    
466
      return nid;
467
  }
468

    
469
  /** Add a new attribute to this node, or set its value */
470
  public long setAttribute(String attName, String attValue, String docid)
471
              throws SAXException
472
  {
473
    long nodeId = -1;
474
    if (attName != null)
475
    {
476
      // Enter the attribute in the hash table
477
      super.setAttribute(attName, attValue);
478

    
479
      // And enter the attribute in the database
480
      nodeId = writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
481
    }
482
    else
483
    {
484
      System.err.println("Attribute name must not be null!");
485
      throw new SAXException("Attribute name must not be null!");
486
    }
487
    return nodeId;
488
  }
489

    
490
  /** Add a namespace to this node */
491
  public long setNamespace(String prefix, String uri, String docid)
492
              throws SAXException
493
  {
494
    long nodeId = -1;
495
    if (prefix != null)
496
    {
497
      // Enter the namespace in a hash table
498
      super.setNamespace(prefix, uri);
499
      // And enter the namespace in the database
500
      nodeId = writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
501
    }
502
    else
503
    {
504
      System.err.println("Namespace prefix must not be null!");
505
      throw new SAXException("Namespace prefix must not be null!");
506
    }
507
    return nodeId;
508
  }
509

    
510

    
511

    
512
  /**
513
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
514
   * Update the node index (xml_index) for this node by generating
515
   * test strings that represent all of the relative and absolute
516
   * paths through the XML tree from document root to this node
517
   */
518
  public void updateNodeIndex(DBConnection conn, String docid, String doctype)
519
               throws SAXException
520
  {
521
    Hashtable pathlist = new Hashtable();
522
    boolean atStartingNode = true;
523
    boolean atRootDocumentNode = false;
524
    DBSAXNode nodePointer = this;
525
    StringBuffer currentPath = new StringBuffer();
526
    int counter = 0;
527

    
528
    // Create a Hashtable of all of the paths to reach this node
529
    // including absolute paths and relative paths
530
    while (!atRootDocumentNode) {
531
      if (atStartingNode) {
532
        currentPath.insert(0, nodePointer.getTagName());
533
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
534
        counter++;
535
        atStartingNode = false;
536
      } else {
537
        currentPath.insert(0, "/");
538
        currentPath.insert(0, nodePointer.getTagName());
539
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
540
        counter++;
541
      }
542

    
543
      // advance to the next parent node
544
      nodePointer = nodePointer.getParentNode();
545

    
546
      // If we're at the DOCUMENT node (root of DOM tree), add
547
      // the root "/" to make the absolute path
548
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
549
        currentPath.insert(0, "/");
550
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
551
        counter++;
552
        atRootDocumentNode = true;
553
      }
554
    }
555

    
556
    try {
557
      // Create an insert statement to reuse for all of the path insertions
558
      PreparedStatement pstmt = conn.prepareStatement(
559
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " +
560
               "parentnodeid) " +
561
              "VALUES (?, ?, ?, ?, ?)");
562
      // Increase usage count
563
      conn.increaseUsageCount(1);
564

    
565
      pstmt.setString(3, docid);
566
      pstmt.setString(4, doctype);
567
      pstmt.setLong(5, getParentID());
568

    
569
      // Step through the hashtable and insert each of the path values
570
      Enumeration en = pathlist.keys();
571
      while (en.hasMoreElements()) {
572
        String path = (String)en.nextElement();
573
        Long nodeid = (Long)pathlist.get(path);
574
        pstmt.setLong(1, nodeid.longValue());
575
        pstmt.setString(2, path);
576

    
577
        pstmt.executeUpdate();
578
      }
579
      // Close the database statement
580
      pstmt.close();
581
    } catch (SQLException sqe) {
582
      System.err.println("SQL Exception while inserting path to index in " +
583
                         "DBSAXNode.updateNodeIndex for document " + docid);
584
      System.err.println(sqe.getMessage());
585
      throw new SAXException(sqe.getMessage());
586
    }
587
  }
588

    
589
  /** get the parent of this node */
590
  public DBSAXNode getParentNode() {
591
    return parentNode;
592
  }
593
}
(19-19/65)