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: bojilova $'
10
 *     '$Date: 2001-09-12 14:49:26 -0700 (Wed, 12 Sep 2001) $'
11
 * '$Revision: 826 $'
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.xml.sax.SAXException;
36

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

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

    
45
  private Connection	conn;
46
  private DBSAXNode	parentNode;
47
  private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
48

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

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

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

    
75
    super(lName);
76
    this.conn = conn;
77
    this.parentNode = parentNode;
78
    setParentID(parentNode.getNodeID());
79
    setRootNodeID(rootnodeid);
80
    setDocID(docid);
81
    setNodeIndex(parentNode.incChildNum());
82
    writeChildNodeToDB("ELEMENT", qName, null, docid);
83
    //No writing XML Index from here. New Thread used instead.
84
    //updateNodeIndex(docid, doctype);
85
  }
86
    
87
  /** creates SQL code and inserts new node into DB connection */
88
  public void writeChildNodeToDB(String nodetype, String nodename,
89
                                 String data, String docid) 
90
                                 throws SAXException {
91
    try {
92
      PreparedStatement pstmt;
93
      if (nodetype == "DOCUMENT") {
94
        pstmt = conn.prepareStatement(
95
            "INSERT INTO xml_nodes " +
96
            "(nodetype, nodename, nodeprefix, docid) " +
97
            "VALUES (?, ?, ?, ?)");
98
        MetaCatUtil.debugMessage("INSERTING DOCNAME: " + nodename);
99
      } else {
100
        pstmt = conn.prepareStatement(
101
            "INSERT INTO xml_nodes " +
102
            "(nodetype, nodename, nodeprefix, docid, " +
103
            "rootnodeid, parentnodeid, nodedata, nodeindex) " +
104
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
105
      }
106

    
107
      // Bind the values to the query
108
      pstmt.setString(1, nodetype);
109
      int idx;
110
      if ( nodename != null && (idx = nodename.indexOf(":")) != -1 ) {
111
        pstmt.setString(2, nodename.substring(idx+1));
112
        pstmt.setString(3, nodename.substring(0,idx));
113
      } else {
114
        pstmt.setString(2, nodename);
115
        pstmt.setString(3, null);
116
      }
117
      pstmt.setString(4, docid);
118
      if (nodetype == "DOCUMENT") {
119
        // moved it to separate method updateRootNodeID
120
        //pstmt.setLong(4, nid);
121
      } else {
122
        if (nodetype == "ELEMENT") {
123
          pstmt.setLong(5, getRootNodeID());
124
          pstmt.setLong(6, getParentID());
125
          pstmt.setString(7, data);
126
          pstmt.setInt(8, getNodeIndex());
127
        } else {
128
          pstmt.setLong(5, getRootNodeID());
129
          pstmt.setLong(6, getNodeID());
130
          pstmt.setString(7, data);
131
          pstmt.setInt(8, incChildNum());
132
        }
133
      }
134
      // Do the insertion
135
      pstmt.execute();
136
      pstmt.close();
137

    
138
      // get the generated unique id afterward
139
      long nid = dbAdapter.getUniqueID(conn, "xml_nodes");
140
      
141
      if (nodetype.equals("DOCUMENT")) {
142
        // Record the root node id that was generated from the database
143
        setRootNodeID(nid);
144
      }
145

    
146
      if (nodetype.equals("DOCUMENT") || nodetype.equals("ELEMENT")) {
147

    
148
        // Record the node id that was generated from the database
149
        setNodeID(nid);
150

    
151
        // Record the node type that was passed to the method
152
        setNodeType(nodetype);
153

    
154
      }
155

    
156
    } catch (SQLException e) {
157
      System.out.println("Error in DBSaxNode.writeChildNodeToDB");
158
      System.err.println("Error inserting node: (" + nodetype + ", " +
159
                                                     nodename + ", " + 
160
                                                     data + ")" );
161
      System.err.println(e.getMessage());
162
      throw new SAXException(e.getMessage());
163
    }
164
  }
165

    
166
  /** 
167
   * update rootnodeid=nodeid for 'DOCUMENT' type of nodes only
168
   */
169
  public void updateRootNodeID(long nodeid) throws SAXException {
170
      try {
171
        PreparedStatement pstmt;
172
        pstmt = conn.prepareStatement(
173
              "UPDATE xml_nodes set rootnodeid = ? " +
174
              "WHERE nodeid = ?");
175

    
176
        // Bind the values to the query
177
        pstmt.setLong(1, nodeid);
178
        pstmt.setLong(2, nodeid);
179
        // Do the update
180
        pstmt.execute();
181
        pstmt.close();
182
      } catch (SQLException e) {
183
        System.out.println("Error in DBSaxNode.updateRootNodeID: " + 
184
                           e.getMessage());
185
        throw new SAXException(e.getMessage());
186
      }
187
  }
188

    
189
  /** 
190
   * creates SQL code to put nodename for the document node 
191
   * into DB connection 
192
   */
193
  public void writeNodename(String nodename) throws SAXException {
194
      try {
195
        PreparedStatement pstmt;
196
        pstmt = conn.prepareStatement(
197
              "UPDATE xml_nodes set nodename = ? " +
198
              "WHERE nodeid = ?");
199

    
200
        // Bind the values to the query
201
        pstmt.setString(1, nodename);
202
        pstmt.setLong(2, getNodeID());
203
        // Do the insertion
204
        pstmt.execute();
205
        pstmt.close();
206
      } catch (SQLException e) {
207
        System.out.println("Error in DBSaxNode.writeNodeName: " + 
208
                           e.getMessage());
209
        throw new SAXException(e.getMessage());
210
      }
211
  }
212

    
213
  /** get next node id from DB connection */
214
  private long generateNodeID() throws SAXException {
215
      long nid=0;
216
      Statement stmt;
217
      try {
218
        stmt = conn.createStatement();
219
        stmt.execute("SELECT xml_nodes_id_seq.nextval FROM dual");
220
        ResultSet rs = stmt.getResultSet();
221
        boolean tableHasRows = rs.next();
222
        if (tableHasRows) {
223
          nid = rs.getLong(1);
224
        }
225
        stmt.close();
226
      } catch (SQLException e) {
227
        System.out.println("Error in DBSaxNode.generateNodeID: " + 
228
                            e.getMessage());
229
        throw new SAXException(e.getMessage());
230
      }
231

    
232
      return nid;
233
  }
234

    
235
  /** Add a new attribute to this node, or set its value */
236
  public void setAttribute(String attName, String attValue, String docid)
237
              throws SAXException {
238
    if (attName != null) {
239
      // Enter the attribute in the hash table
240
      super.setAttribute(attName, attValue);
241

    
242
      // And enter the attribute in the database
243
      writeChildNodeToDB("ATTRIBUTE", attName, attValue, docid);
244
    } else {
245
      System.err.println("Attribute name must not be null!");
246
      throw new SAXException("Attribute name must not be null!");
247
    }
248
  }
249

    
250
  /** Add a namespace to this node */
251
  public void setNamespace(String prefix, String uri, String docid)
252
              throws SAXException {
253
    if (prefix != null) {
254
      // Enter the namespace in a hash table
255
      super.setNamespace(prefix, uri);
256
      // And enter the namespace in the database
257
      writeChildNodeToDB("NAMESPACE", prefix, uri, docid);
258
    } else {
259
      System.err.println("Namespace prefix must not be null!");
260
      throw new SAXException("Namespace prefix must not be null!");
261
    }
262
  }
263

    
264
  /** 
265
   * NOT USED
266
   * Update the node index (xml_index) for this node by generating
267
   * test strings that represent all of the relative and absolute
268
   * paths through the XML tree from document root to this node
269
   */
270
  private void updateNodeIndex(String docid, String doctype) 
271
               throws SAXException
272
  {
273
    Hashtable pathlist = new Hashtable();
274
    boolean atStartingNode = true;
275
    boolean atRootDocumentNode = false;
276
    DBSAXNode nodePointer = this;
277
    StringBuffer currentPath = new StringBuffer();
278
    int counter = 0;
279

    
280
    // Create a Hashtable of all of the paths to reach this node
281
    // including absolute paths and relative paths
282
    while (!atRootDocumentNode) {
283
      if (atStartingNode) {
284
        currentPath.insert(0, nodePointer.getTagName());
285
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
286
        counter++;
287
        atStartingNode = false;
288
      } else {
289
        currentPath.insert(0, "/");
290
        currentPath.insert(0, nodePointer.getTagName());
291
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
292
        counter++;
293
      }
294

    
295
      // advance to the next parent node
296
      nodePointer = nodePointer.getParentNode();
297

    
298
      // If we're at the DOCUMENT node (root of DOM tree), add
299
      // the root "/" to make the absolute path
300
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
301
        currentPath.insert(0, "/");
302
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
303
        counter++;
304
        atRootDocumentNode = true;
305
      } 
306
    }
307

    
308
    try {
309
      // Create an insert statement to reuse for all of the path insertions
310
      PreparedStatement pstmt = conn.prepareStatement(
311
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " + 
312
               "parentnodeid) " + 
313
              "VALUES (?, ?, ?, ?, ?)");
314
      //((OraclePreparedStatement)pstmt).setExecuteBatch(counter);
315
  
316
      pstmt.setString(3, docid);
317
      pstmt.setString(4, doctype);
318
      pstmt.setLong(5, getParentID());
319
      
320
      // Step through the hashtable and insert each of the path values
321
      Enumeration en = pathlist.keys();
322
      while (en.hasMoreElements()) {
323
        String path = (String)en.nextElement();
324
        Long nodeid = (Long)pathlist.get(path);
325
        pstmt.setLong(1, nodeid.longValue());
326
        pstmt.setString(2, path);
327
        pstmt.executeUpdate();
328
  
329
        //System.out.println(nodeid + " ==> " + path);
330
      }
331

    
332
      // Close the database statement
333
      pstmt.close();
334
    } catch (SQLException sqe) {
335
      System.err.println("SQL Exception while inserting path to index in " + 
336
                         "DBSAXNode.updateNodeIndex");
337
      System.err.println(sqe.getMessage());
338
      throw new SAXException(sqe.getMessage());
339
    }
340
  }
341

    
342
  /** 
343
   * USED FROM SEPARATE THREAD RUNNED from DBSAXHandler on endDocument()
344
   * Update the node index (xml_index) for this node by generating
345
   * test strings that represent all of the relative and absolute
346
   * paths through the XML tree from document root to this node
347
   */
348
  public void updateNodeIndex(Connection conn, String docid, String doctype) 
349
               throws SAXException
350
  {
351
    Hashtable pathlist = new Hashtable();
352
    boolean atStartingNode = true;
353
    boolean atRootDocumentNode = false;
354
    DBSAXNode nodePointer = this;
355
    StringBuffer currentPath = new StringBuffer();
356
    int counter = 0;
357

    
358
    // Create a Hashtable of all of the paths to reach this node
359
    // including absolute paths and relative paths
360
    while (!atRootDocumentNode) {
361
      if (atStartingNode) {
362
        currentPath.insert(0, nodePointer.getTagName());
363
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
364
        counter++;
365
        atStartingNode = false;
366
      } else {
367
        currentPath.insert(0, "/");
368
        currentPath.insert(0, nodePointer.getTagName());
369
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
370
        counter++;
371
      }
372

    
373
      // advance to the next parent node
374
      nodePointer = nodePointer.getParentNode();
375

    
376
      // If we're at the DOCUMENT node (root of DOM tree), add
377
      // the root "/" to make the absolute path
378
      if (nodePointer.getNodeType().equals("DOCUMENT")) {
379
        currentPath.insert(0, "/");
380
        pathlist.put(currentPath.toString(), new Long(getNodeID()));
381
        counter++;
382
        atRootDocumentNode = true;
383
      } 
384
    }
385

    
386
    try {
387
      // Create an insert statement to reuse for all of the path insertions
388
      PreparedStatement pstmt = conn.prepareStatement(
389
              "INSERT INTO xml_index (nodeid, path, docid, doctype, " + 
390
               "parentnodeid) " + 
391
              "VALUES (?, ?, ?, ?, ?)");
392
      //((OraclePreparedStatement)pstmt).setExecuteBatch(counter);
393
  
394
      pstmt.setString(3, docid);
395
      pstmt.setString(4, doctype);
396
      pstmt.setLong(5, getParentID());
397
      
398
      // Step through the hashtable and insert each of the path values
399
      Enumeration en = pathlist.keys();
400
      while (en.hasMoreElements()) {
401
        String path = (String)en.nextElement();
402
        Long nodeid = (Long)pathlist.get(path);
403
        pstmt.setLong(1, nodeid.longValue());
404
        pstmt.setString(2, path);
405
        pstmt.executeUpdate();
406
  
407
        //System.out.println(nodeid + " ==> " + path);
408
      }
409

    
410
      // Close the database statement
411
      pstmt.close();
412
    } catch (SQLException sqe) {
413
      System.err.println("SQL Exception while inserting path to index in " +
414
                         "DBSAXNode.updateNodeIndex");
415
      System.err.println(sqe.getMessage());
416
      throw new SAXException(sqe.getMessage());
417
    }
418
  }
419
 
420
  /** get the parent of this node */
421
  public DBSAXNode getParentNode() {
422
    return parentNode;
423
  }
424
}
(16-16/40)