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: berkley $'
11
 *     '$Date: 2001-12-20 12:13:11 -0800 (Thu, 20 Dec 2001) $'
12
 * '$Revision: 887 $'
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.Hashtable;
36
import java.util.Enumeration;
37
import java.util.EmptyStackException;
38

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

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

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

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

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

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

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

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

    
147
   /** SAX Handler that is called at the start of Namespace */
148
   public void startPrefixMapping(String prefix, String uri) 
149
                                          throws SAXException
150
   {
151
    MetaCatUtil.debugMessage("NAMESPACE");
152

    
153
    namespaces.put(prefix, uri);
154
   }
155
   
156
   /** SAX Handler that is called at the start of each XML element */
157
   public void startElement(String uri, String localName,
158
                            String qName, Attributes atts) 
159
               throws SAXException {
160
     MetaCatUtil.debugMessage("Start ELEMENT " + qName);
161
 
162
     DBSAXNode parentNode = null;
163
     DBSAXNode currentNode = null;
164

    
165
     // Get a reference to the parent node for the id
166
     try {
167
       parentNode = (DBSAXNode)nodeStack.peek();
168
     } catch (EmptyStackException e) {
169
       parentNode = null;
170
     }
171

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

    
210
     // Create the current node representation
211
     currentNode = new DBSAXNode(conn, qName, localName, parentNode,
212
                                 currentDocument.getRootNodeID(),docid,
213
                                 currentDocument.getDoctype());
214
                               
215
     // Add all of the namespaces
216
     String prefix;
217
     String nsuri;
218
     Enumeration prefixes = namespaces.keys();
219
     while ( prefixes.hasMoreElements() ) {
220
       prefix = (String)prefixes.nextElement();
221
       nsuri = (String)namespaces.get(prefix);
222
       currentNode.setNamespace(prefix, nsuri, docid);
223
     }
224
     namespaces = null;
225
     namespaces = new Hashtable();
226

    
227
     // Add all of the attributes
228
     for (int i=0; i<atts.getLength(); i++) {
229
       currentNode.setAttribute(atts.getQName(i), atts.getValue(i), docid);
230
     }      
231

    
232
     // Add the node to the stack, so that any text data can be 
233
     // added as it is encountered
234
     nodeStack.push(currentNode);
235
     // Add the node to the vector used by thread for writing XML Index
236
     nodeIndex.addElement(currentNode);
237

    
238
  }
239
  
240
  /* The run method of xmlIndex thread. It writes XML Index for the document. */
241
  public void run () {
242
    DBSAXNode currNode = null;
243
    DBSAXNode prevNode = null;
244
    Connection dbconn = null;
245
    String doctype = currentDocument.getDoctype();
246
    int step = 0;
247
    int counter = 0;
248

    
249
    try {
250
      // Opening separate db connection for writing XML Index
251
      MetaCatUtil util = new MetaCatUtil();
252
      dbconn = util.openDBConnection();
253
      dbconn.setAutoCommit(false);
254

    
255
      // Going through the elements of the document and writing its Index
256
      Enumeration nodes = nodeIndex.elements();
257
      while ( nodes.hasMoreElements() ) {
258
        currNode = (DBSAXNode)nodes.nextElement();
259
        currNode.updateNodeIndex(dbconn, docid, doctype);
260
      }
261
    
262
      dbconn.commit();
263
         
264
      //if this is a package file
265
      String packagedoctype = util.getOption("packagedoctype");
266
      Vector packagedoctypes = new Vector();
267
      
268
      packagedoctypes = MetaCatUtil.getOptionList(packagedoctype);
269
      
270
      if ( packagedoctypes.contains(doctype) )
271
      {
272
        // write the package info to xml_relation table
273
        RelationHandler rth = new RelationHandler(docid, dbconn);
274
        // from the relations get the access file id for that package
275
        String aclid = rth.getAccessFileID(docid);
276
        // if there are access file, write ACL for that package
277
        if ( aclid != null ) {
278
          runAccessControlList(dbconn, aclid);
279
        }
280
      }
281
      // if it is an access file
282
      else if ( MetaCatUtil.getOptionList(
283
                            util.getOption("accessdoctype")).contains(doctype) )
284
      {
285
        // write ACL for the package
286
        runAccessControlList(dbconn, docid);
287
      }
288
      
289
      dbconn.close();
290

    
291
    } catch (Exception e) {
292
      try {
293
        dbconn.rollback();
294
        dbconn.close();
295
      } catch (SQLException sqle) {}
296
      System.out.println("Error in DBSAXHandler.run " + e.getMessage());
297
      e.printStackTrace();
298
    }      
299
  }
300
  
301
  // It runs in xmlIndex thread. It writes ACL for a package.
302
  private void runAccessControlList (Connection conn, String aclid)
303
                                                throws Exception
304
  {
305
    // read the access file from xml_nodes
306
    // parse the access file and store the access info into xml_access
307
    AccessControlList aclobj = 
308
    new AccessControlList(conn, aclid, //new StringReader(xml),
309
                          user, groups, serverCode);
310
    conn.commit();
311
  }
312

    
313

    
314
  /** SAX Handler that is called for each XML text node */
315
  public void characters(char[] cbuf, int start, int len) throws SAXException {
316
     MetaCatUtil.debugMessage("CHARACTERS");
317
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
318
     String data = null;
319
     int leftover = len;
320
     int offset = start;
321
     boolean moredata = true;
322
    
323
     // This loop deals with the case where there are more characters 
324
     // than can fit in a single database text field (limit is 
325
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
326
     // write a series of nodes that are MAXDATACHARS long, and then the
327
     // final node contains the remainder
328
     while (moredata) {
329
       if (leftover > MAXDATACHARS) {
330
         data = new String(cbuf, offset, MAXDATACHARS);
331
         leftover -= MAXDATACHARS;
332
         offset += MAXDATACHARS;
333
       } else {
334
         data = new String(cbuf, offset, leftover);
335
         moredata = false;
336
       }
337

    
338
       // Write the content of the node to the database
339
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
340
     }
341
   }
342

    
343
   /** 
344
    * SAX Handler that is called for each XML text node that is
345
    * Ignorable white space
346
    */
347
   public void ignorableWhitespace(char[] cbuf, int start, int len)
348
               throws SAXException {
349
     // When validation is turned "on", white spaces are reported here
350
     // When validation is turned "off" white spaces are not reported here,
351
     // but through characters() callback
352
     MetaCatUtil.debugMessage("IGNORABLEWHITESPACE");
353
     //System.out.println("Whitespace:" + len + "x" + new String(cbuf, start, len) + "x");
354

    
355
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
356
     String data = null;
357
     int leftover = len;
358
     int offset = start;
359
     boolean moredata = true;
360
     
361
     // This loop deals with the case where there are more characters 
362
     // than can fit in a single database text field (limit is 
363
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
364
     // write a series of nodes that are MAXDATACHARS long, and then the
365
     // final node contains the remainder
366
     while (moredata) {
367
       if (leftover > MAXDATACHARS) {
368
         data = new String(cbuf, offset, MAXDATACHARS);
369
         leftover -= MAXDATACHARS;
370
         offset += MAXDATACHARS;
371
       } else {
372
         data = new String(cbuf, offset, leftover);
373
         moredata = false;
374
       }
375

    
376
       // Write the content of the node to the database
377
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
378
     }
379
   }
380

    
381
   /** 
382
    * SAX Handler called once for each processing instruction found: 
383
    * node that PI may occur before or after the root element.
384
    */
385
   public void processingInstruction(String target, String data) 
386
          throws SAXException {
387
     MetaCatUtil.debugMessage("PI");
388
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
389
     currentNode.writeChildNodeToDB("PI", target, data, docid);
390
   }
391

    
392
   /** SAX Handler that is called at the end of each XML element */
393
   public void endElement(String uri, String localName,
394
                          String qName) throws SAXException {
395
     MetaCatUtil.debugMessage("End ELEMENT " + qName);
396

    
397
     // Get the node from the stack
398
     DBSAXNode currentNode = (DBSAXNode)nodeStack.pop();
399
   }
400

    
401
   //
402
   // the next section implements the LexicalHandler interface
403
   //
404

    
405
   /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
406
   public void startDTD(String name, String publicId, String systemId) 
407
               throws SAXException {
408
     docname = name;
409
     doctype = publicId;
410
     systemid = systemId;
411

    
412
     MetaCatUtil.debugMessage("Start DTD");
413
     MetaCatUtil.debugMessage("DOCNAME: " + docname);
414
     MetaCatUtil.debugMessage("DOCTYPE: " + doctype);
415
     MetaCatUtil.debugMessage("  SYSID: " + systemid);
416
   }
417

    
418
   /** 
419
    * SAX Handler that receives notification of end of DTD 
420
    */
421
   public void endDTD() throws SAXException {
422
    
423
     MetaCatUtil.debugMessage("end DTD");
424
   }
425

    
426
   /** 
427
    * SAX Handler that receives notification of comments in the DTD
428
    */
429
   public void comment(char[] ch, int start, int length) throws SAXException {
430
     MetaCatUtil.debugMessage("COMMENT");
431
     if ( !processingDTD ) {
432
       DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
433
       currentNode.writeChildNodeToDB("COMMENT", null, new String(ch), docid);
434
     }
435
   }
436

    
437
   /** 
438
    * SAX Handler that receives notification of the start of CDATA sections
439
    */
440
   public void startCDATA() throws SAXException {
441
     MetaCatUtil.debugMessage("start CDATA");
442
   }
443

    
444
   /** 
445
    * SAX Handler that receives notification of the end of CDATA sections
446
    */
447
   public void endCDATA() throws SAXException {
448
     MetaCatUtil.debugMessage("end CDATA");
449
   }
450

    
451
   /** 
452
    * SAX Handler that receives notification of the start of entities
453
    */
454
   public void startEntity(String name) throws SAXException {
455
     MetaCatUtil.debugMessage("start ENTITY: " + name);
456
//System.out.println("start ENTITY: " + name);
457
     if (name.equals("[dtd]")) {
458
       processingDTD = true;
459
     }
460
   }
461

    
462
   /** 
463
    * SAX Handler that receives notification of the end of entities
464
    */
465
   public void endEntity(String name) throws SAXException {
466
     MetaCatUtil.debugMessage("end ENTITY: " + name);
467
//System.out.println("end ENTITY: " + name);
468
     if (name.equals("[dtd]")) {
469
       processingDTD = false;
470
     }
471
   }
472

    
473
   /** 
474
    * SAX Handler that receives notification of element declarations
475
    */
476
   public void elementDecl(String name, String model)
477
                        throws org.xml.sax.SAXException {
478
//System.out.println("ELEMENTDECL: " + name + " " + model);
479
     MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model);
480
   }
481

    
482
   /** 
483
    * SAX Handler that receives notification of attribute declarations
484
    */
485
   public void attributeDecl(String eName, String aName,
486
                        String type, String valueDefault, String value)
487
                        throws org.xml.sax.SAXException {
488

    
489
//System.out.println("ATTRIBUTEDECL: " + eName + " " 
490
//                        + aName + " " + type + " " + valueDefault + " "
491
//                        + value);
492
     MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " 
493
                        + aName + " " + type + " " + valueDefault + " "
494
                        + value);
495
   }
496

    
497
   /** 
498
    * SAX Handler that receives notification of internal entity declarations
499
    */
500
   public void internalEntityDecl(String name, String value)
501
                        throws org.xml.sax.SAXException {
502
//System.out.println("INTERNENTITYDECL: " + name + " " + value);
503
     MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value);
504
   }
505

    
506
   /** 
507
    * SAX Handler that receives notification of external entity declarations
508
    */
509
   public void externalEntityDecl(String name, String publicId,
510
                        String systemId)
511
                        throws org.xml.sax.SAXException {
512
//System.out.println("EXTERNENTITYDECL: " + name + " " + publicId 
513
//                              + " " + systemId);
514
     MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId 
515
                              + " " + systemId);
516
     // it processes other external entity, not the DTD;
517
     // it doesn't signal for the DTD here
518
     processingDTD = false;
519
   }
520

    
521
   //
522
   // the next section implements the ErrorHandler interface
523
   //
524

    
525
   /** 
526
    * SAX Handler that receives notification of fatal parsing errors
527
    */
528
   public void fatalError(SAXParseException exception) throws SAXException {
529
     MetaCatUtil.debugMessage("FATALERROR");
530
     throw (new SAXException("Fatal processing error.", exception));
531
   }
532

    
533
   /** 
534
    * SAX Handler that receives notification of recoverable parsing errors
535
    */
536
   public void error(SAXParseException exception) throws SAXException {
537
     MetaCatUtil.debugMessage("ERROR");
538
     throw (new SAXException("Processing error.", exception));
539
   }
540

    
541
   /** 
542
    * SAX Handler that receives notification of warnings
543
    */
544
   public void warning(SAXParseException exception) throws SAXException {
545
     MetaCatUtil.debugMessage("WARNING");
546
     throw (new SAXException("Warning.", exception));
547
   }
548

    
549
   // 
550
   // Helper, getter and setter methods
551
   //
552
   
553
   /**
554
    * get the document name
555
    */
556
   public String getDocname() {
557
     return docname;
558
   }
559

    
560
   /**
561
    * get the document processing state
562
    */
563
   public boolean processingDTD() {
564
     return processingDTD;
565
   }
566
}
(15-15/40)