Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that handles the SAX XML events as they
4
 *             are generated from XML documents
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Matt Jones, Jivka Bojilova
8
 *    Release: @release@
9
 *
10
 *   '$Author: bojilova $'
11
 *     '$Date: 2001-07-20 21:03:32 -0700 (Fri, 20 Jul 2001) $'
12
 * '$Revision: 802 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.sql.*;
32
import java.io.StringReader;
33
import java.util.Stack;
34
import java.util.Vector;
35
import java.util.Enumeration;
36
import java.util.EmptyStackException;
37

    
38
import org.xml.sax.Attributes;
39
import org.xml.sax.SAXException;
40
import org.xml.sax.SAXParseException;
41
import org.xml.sax.ext.DeclHandler;
42
import org.xml.sax.ext.LexicalHandler;
43
import org.xml.sax.helpers.DefaultHandler;
44

    
45
/** 
46
 * A database aware Class implementing callback bethods for the SAX parser to
47
 * call when processing the XML stream and generating events
48
 */
49
public class DBSAXHandler extends DefaultHandler 
50
                          implements LexicalHandler, DeclHandler, Runnable {
51

    
52
   private boolean	atFirstElement;
53
   private boolean	processingDTD;
54
   private String 	docname = null;
55
   private String 	doctype;
56
   private String 	systemid;
57
   private boolean 	stackCreated = false;
58
   private Stack 	  nodeStack;
59
   private Vector   nodeIndex;
60
   private Connection	  conn = null;
61
   private DocumentImpl currentDocument;
62
   private DBSAXNode    rootNode;
63
   private String   action = null;
64
   private String   docid = null;
65
   private String   user = null;
66
   private String[] groups = null;
67
   private String   pub = null;
68
   private Thread   xmlIndex;
69
   private boolean endDocument = false;
70
   private int serverCode = 1;
71

    
72
   private static final int MAXDATACHARS = 4000;
73
// DOCTITLE attr cleared from the db
74
//   private static final int MAXTITLELEN = 1000;
75

    
76
   /** Construct an instance of the handler class 
77
    *
78
    * @param conn the JDBC connection to which information is written
79
    */
80
   public DBSAXHandler(Connection conn) {
81
     this.conn = conn;
82
     this.atFirstElement = true;
83
     this.processingDTD = false;
84

    
85
     // Create the stack for keeping track of node context
86
     // if it doesn't already exist
87
     if (!stackCreated) {
88
       nodeStack = new Stack();
89
       nodeIndex = new Vector();
90
       stackCreated = true;
91
     }
92
   }
93
   
94
   /** Construct an instance of the handler class 
95
    *
96
    * @param conn the JDBC connection to which information is written
97
    * @param action - "INSERT" or "UPDATE"
98
    * @param docid to be inserted or updated into JDBC connection
99
    * @param user the user connected to MetaCat servlet and owns the document
100
    * @param groups the groups to which user belongs
101
    * @param pub flag for public "read" access on document
102
    * @param serverCode the serverid from xml_replication on which this document
103
    *        resides.
104
    *
105
    */
106
   public DBSAXHandler(Connection conn, String action, String docid,
107
                       String user, String[] groups, String pub, int serverCode)
108
   {
109
     this(conn);
110
     this.action = action;
111
     this.docid = docid;
112
     this.user = user;
113
     this.groups = groups;
114
     this.pub = pub;
115
     this.serverCode = serverCode;
116
     this.xmlIndex = new Thread(this);
117
   }
118
 
119
   /** SAX Handler that receives notification of beginning of the document */
120
   public void startDocument() throws SAXException {
121
     MetaCatUtil.debugMessage("start Document");
122

    
123
     // Create the document node representation as root
124
     rootNode = new DBSAXNode(conn, this.docid);
125
     // Add the node to the stack, so that any text data can be 
126
     // added as it is encountered
127
     nodeStack.push(rootNode);
128
   }
129

    
130
   /** SAX Handler that receives notification of end of the document */
131
   public void endDocument() throws SAXException {
132
     MetaCatUtil.debugMessage("end Document");
133
     // Starting new thread for writing XML Index.
134
     // It calls the run method of the thread.
135
     try {
136
       xmlIndex.start();
137
     } catch (NullPointerException e) {
138
       xmlIndex = null;
139
       throw new 
140
       SAXException("Problem with starting thread for writing XML Index. " +
141
                    e.getMessage());
142
     }
143
   }
144

    
145
   /** SAX Handler that is called at the start of each XML element */
146
   public void startElement(String uri, String localName,
147
                            String qName, Attributes atts) 
148
               throws SAXException {
149
     MetaCatUtil.debugMessage("Start ELEMENT " + localName);
150

    
151
     DBSAXNode parentNode = null;
152
     DBSAXNode currentNode = null;
153

    
154
     // Get a reference to the parent node for the id
155
     try {
156
       parentNode = (DBSAXNode)nodeStack.peek();
157
     } catch (EmptyStackException e) {
158
       parentNode = null;
159
     }
160

    
161
     // Document representation that points to the root document node
162
     if (atFirstElement) {
163
       atFirstElement = false;
164
       // If no DOCTYPE declaration: docname = root element name 
165
       if (docname == null) {
166
         docname = localName;
167
         doctype = docname;
168
         MetaCatUtil.debugMessage("DOCNAME-a: " + docname);
169
         MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype);
170
       } else if (doctype == null) {
171
         doctype = docname;
172
         MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype);
173
       }
174
       rootNode.writeNodename(docname);
175
       try {
176
         // for validated XML Documents store a reference to XML DB Catalog
177
         String catalogid = null;
178
         if ( systemid != null ) {
179
           Statement stmt = conn.createStatement();
180
           ResultSet rs = stmt.executeQuery(
181
                          "SELECT catalog_id FROM xml_catalog " +
182
                          "WHERE entry_type = 'DTD' " + 
183
                          "AND public_id = '" + doctype + "'");
184
           boolean hasRow = rs.next();
185
           if ( hasRow ) {
186
            catalogid = rs.getString(1);
187
           }
188
           stmt.close();
189
         }
190
         currentDocument = new DocumentImpl(conn, rootNode.getNodeID(), 
191
                               docname, doctype, docid, action, user, 
192
                               this.pub, catalogid, this.serverCode);
193
       } catch (Exception ane) {
194
         throw (new SAXException("Error in DBSaxHandler.startElement " + 
195
                                 action, ane));
196
       }
197
     }      
198

    
199
     // Create the current node representation
200
     currentNode = new DBSAXNode(conn, localName, parentNode,
201
                                 currentDocument.getRootNodeID(),docid,
202
                                 currentDocument.getDoctype());
203
                               
204
     // Add all of the attributes
205
     for (int i=0; i<atts.getLength(); i++) {
206
       currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i), docid);
207
     }      
208

    
209
     // Add the node to the stack, so that any text data can be 
210
     // added as it is encountered
211
     nodeStack.push(currentNode);
212
     // Add the node to the vector used by thread for writing XML Index
213
     nodeIndex.addElement(currentNode);
214

    
215
  }
216
  
217
  // The run method of xmlIndex thread. It writes XML Index for the document.
218
  public void run () {
219
    DBSAXNode currNode = null;
220
    DBSAXNode prevNode = null;
221
    Connection dbconn = null;
222
    String doctype = currentDocument.getDoctype();
223
    int step = 0;
224
    int counter = 0;
225

    
226
    try {
227
      // Opening separate db connection for writing XML Index
228
      MetaCatUtil util = new MetaCatUtil();
229
      dbconn = util.openDBConnection();
230
      dbconn.setAutoCommit(false);
231

    
232
      // Going through the elements of the document and writing its Index
233
      Enumeration nodes = nodeIndex.elements();
234
      while ( nodes.hasMoreElements() ) {
235
        currNode = (DBSAXNode)nodes.nextElement();
236
        currNode.updateNodeIndex(dbconn, docid, doctype);
237
      }
238
    
239
      dbconn.commit();
240
         
241
      //if this is a package file then write the package info to 
242
      //the xml_relation table. RelationHandler checks to see
243
      //if it is a package file so you don't have to do it here.
244
      if ( doctype.equals(util.getOption("packagedoctype")) )
245
      {
246
        //DocumentImpl xmldoc = new DocumentImpl(dbconn, docid);
247
        RelationHandler rth = new RelationHandler(docid, dbconn);
248
      } 
249
      else if ( doctype.equals(util.getOption("accessdoctype")) ) 
250
      {
251
        DocumentImpl xmldoc = new DocumentImpl(dbconn, docid);
252
        String xml = xmldoc.toString();
253
        try {
254
          AccessControlList aclobj = 
255
          new AccessControlList(dbconn, docid, new StringReader(xml),
256
                                user, groups, serverCode);
257
          dbconn.commit();
258
        } catch (SAXException e) {
259
          try {
260
            dbconn.rollback();
261
            dbconn.close();
262
          } catch (SQLException sqle) {}
263
          System.out.println("Error writing ACL in DBSaxHandler.run " + 
264
                             e.getMessage()); 
265
        }
266
      }
267
      
268
      
269
      dbconn.close();
270

    
271
    } catch (Exception e) {
272
      try {
273
        dbconn.rollback();
274
        dbconn.close();
275
      } catch (SQLException sqle) {}
276
      System.out.println("Error writing XML Index in DBSaxHandler.run " + 
277
                         e.getMessage()); 
278
    }      
279
  }
280

    
281
  /** SAX Handler that is called for each XML text node */
282
  public void characters(char[] cbuf, int start, int len) throws SAXException {
283
     MetaCatUtil.debugMessage("CHARACTERS");
284
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
285
     String data = null;
286
     int leftover = len;
287
     int offset = start;
288
     boolean moredata = true;
289
    
290
     // This loop deals with the case where there are more characters 
291
     // than can fit in a single database text field (limit is 
292
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
293
     // write a series of nodes that are MAXDATACHARS long, and then the
294
     // final node contains the remainder
295
     while (moredata) {
296
       if (leftover > MAXDATACHARS) {
297
         data = new String(cbuf, offset, MAXDATACHARS);
298
         leftover -= MAXDATACHARS;
299
         offset += MAXDATACHARS;
300
       } else {
301
         data = new String(cbuf, offset, leftover);
302
         moredata = false;
303
       }
304

    
305
       // Write the content of the node to the database
306
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
307
     }
308

    
309
// DOCTITLE attr cleared from the db
310
//     // write the title of document if there are tag <title>
311
//     if ( currentNode.getTagName().equals("title") ) {
312
//       if ( leftover > MAXTITLELEN ) 
313
//         currentDocument.setTitle(new String(cbuf, start, MAXTITLELEN));
314
//       else
315
//         currentDocument.setTitle(new String(cbuf, start, leftover));
316
//     }
317
   }
318

    
319
   /** 
320
    * SAX Handler that is called for each XML text node that is
321
    * Ignorable white space
322
    */
323
   public void ignorableWhitespace(char[] cbuf, int start, int len)
324
               throws SAXException {
325
     // When validation is turned "on", white spaces are reported here
326
     // When validation is turned "off" white spaces are not reported here,
327
     // but through characters() callback
328
     MetaCatUtil.debugMessage("IGNORABLEWHITESPACE");
329
     //System.out.println("Whitespace:" + len + "x" + new String(cbuf, start, len) + "x");
330

    
331
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
332
     String data = null;
333
     int leftover = len;
334
     int offset = start;
335
     boolean moredata = true;
336
     
337
     // This loop deals with the case where there are more characters 
338
     // than can fit in a single database text field (limit is 
339
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
340
     // write a series of nodes that are MAXDATACHARS long, and then the
341
     // final node contains the remainder
342
     while (moredata) {
343
       if (leftover > MAXDATACHARS) {
344
         data = new String(cbuf, offset, MAXDATACHARS);
345
         leftover -= MAXDATACHARS;
346
         offset += MAXDATACHARS;
347
       } else {
348
         data = new String(cbuf, offset, leftover);
349
         moredata = false;
350
       }
351

    
352
       // Write the content of the node to the database
353
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
354
     }
355
   }
356

    
357
   /** 
358
    * SAX Handler called once for each processing instruction found: 
359
    * node that PI may occur before or after the root element.
360
    */
361
   public void processingInstruction(String target, String data) 
362
          throws SAXException {
363
     MetaCatUtil.debugMessage("PI");
364
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
365
     currentNode.writeChildNodeToDB("PI", target, data, docid);
366
   }
367

    
368
   /** SAX Handler that is called at the end of each XML element */
369
   public void endElement(String uri, String localName,
370
                          String qName) throws SAXException {
371
     MetaCatUtil.debugMessage("End ELEMENT " + localName);
372

    
373
     // Get the node from the stack
374
     DBSAXNode currentNode = (DBSAXNode)nodeStack.pop();
375
   }
376

    
377
   //
378
   // the next section implements the LexicalHandler interface
379
   //
380

    
381
   /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
382
   public void startDTD(String name, String publicId, String systemId) 
383
               throws SAXException {
384
     docname = name;
385
     doctype = publicId;
386
     systemid = systemId;
387

    
388
//System.out.println("Start DTD");
389
//System.out.println("DOCNAME: " + docname);
390
//System.out.println("DOCTYPE: " + doctype);
391
//System.out.println("  SYSID: " + systemid);
392

    
393
     MetaCatUtil.debugMessage("Start DTD");
394
     MetaCatUtil.debugMessage("DOCNAME: " + docname);
395
     MetaCatUtil.debugMessage("DOCTYPE: " + doctype);
396
     MetaCatUtil.debugMessage("  SYSID: " + systemid);
397
   }
398

    
399
   /** 
400
    * SAX Handler that receives notification of end of DTD 
401
    */
402
   public void endDTD() throws SAXException {
403
    
404
//System.out.println("end DTD");
405
     MetaCatUtil.debugMessage("end DTD");
406
   }
407

    
408
   /** 
409
    * SAX Handler that receives notification of comments in the DTD
410
    */
411
   public void comment(char[] ch, int start, int length) throws SAXException {
412
     MetaCatUtil.debugMessage("COMMENT");
413
     if ( !processingDTD ) {
414
       DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
415
       currentNode.writeChildNodeToDB("COMMENT", null, new String(ch), docid);
416
     }
417
   }
418

    
419
   /** 
420
    * SAX Handler that receives notification of the start of CDATA sections
421
    */
422
   public void startCDATA() throws SAXException {
423
     MetaCatUtil.debugMessage("start CDATA");
424
   }
425

    
426
   /** 
427
    * SAX Handler that receives notification of the end of CDATA sections
428
    */
429
   public void endCDATA() throws SAXException {
430
     MetaCatUtil.debugMessage("end CDATA");
431
   }
432

    
433
   /** 
434
    * SAX Handler that receives notification of the start of entities
435
    */
436
   public void startEntity(String name) throws SAXException {
437
     MetaCatUtil.debugMessage("start ENTITY: " + name);
438
//System.out.println("start ENTITY: " + name);
439
     if (name.equals("[dtd]")) {
440
       processingDTD = true;
441
     }
442
   }
443

    
444
   /** 
445
    * SAX Handler that receives notification of the end of entities
446
    */
447
   public void endEntity(String name) throws SAXException {
448
     MetaCatUtil.debugMessage("end ENTITY: " + name);
449
//System.out.println("end ENTITY: " + name);
450
     if (name.equals("[dtd]")) {
451
       processingDTD = false;
452
     }
453
   }
454

    
455
   /** 
456
    * SAX Handler that receives notification of element declarations
457
    */
458
   public void elementDecl(String name, String model)
459
                        throws org.xml.sax.SAXException {
460
//System.out.println("ELEMENTDECL: " + name + " " + model);
461
     MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model);
462
   }
463

    
464
   /** 
465
    * SAX Handler that receives notification of attribute declarations
466
    */
467
   public void attributeDecl(String eName, String aName,
468
                        String type, String valueDefault, String value)
469
                        throws org.xml.sax.SAXException {
470
//System.out.println("ATTRIBUTEDECL: " + eName + " " 
471
//                        + aName + " " + type + " " + valueDefault + " "
472
//                        + value);
473
     MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " 
474
                        + aName + " " + type + " " + valueDefault + " "
475
                        + value);
476
   }
477

    
478
   /** 
479
    * SAX Handler that receives notification of internal entity declarations
480
    */
481
   public void internalEntityDecl(String name, String value)
482
                        throws org.xml.sax.SAXException {
483
//System.out.println("INTERNENTITYDECL: " + name + " " + value);
484
     MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value);
485
   }
486

    
487
   /** 
488
    * SAX Handler that receives notification of external entity declarations
489
    */
490
   public void externalEntityDecl(String name, String publicId,
491
                        String systemId)
492
                        throws org.xml.sax.SAXException {
493
//System.out.println("EXTERNENTITYDECL: " + name + " " + publicId 
494
//                              + " " + systemId);
495
     MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId 
496
                              + " " + systemId);
497
   }
498

    
499
   //
500
   // the next section implements the ErrorHandler interface
501
   //
502

    
503
   /** 
504
    * SAX Handler that receives notification of fatal parsing errors
505
    */
506
   public void fatalError(SAXParseException exception) throws SAXException {
507
     MetaCatUtil.debugMessage("FATALERROR");
508
     throw (new SAXException("Fatal processing error.", exception));
509
   }
510

    
511
   /** 
512
    * SAX Handler that receives notification of recoverable parsing errors
513
    */
514
   public void error(SAXParseException exception) throws SAXException {
515
     MetaCatUtil.debugMessage("ERROR");
516
     throw (new SAXException("Processing error.", exception));
517
   }
518

    
519
   /** 
520
    * SAX Handler that receives notification of warnings
521
    */
522
   public void warning(SAXParseException exception) throws SAXException {
523
     MetaCatUtil.debugMessage("WARNING");
524
     throw (new SAXException("Warning.", exception));
525
   }
526

    
527
   // 
528
   // Helper, getter and setter methods
529
   //
530
   
531
   /**
532
    * get the document name
533
    */
534
   public String getDocname() {
535
     return docname;
536
   }
537

    
538
   /**
539
    * get the document processing state
540
    */
541
   public boolean processingDTD() {
542
     return processingDTD;
543
   }
544
}
(15-15/40)