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: jones $'
11
 *     '$Date: 2001-01-18 11:52:00 -0800 (Thu, 18 Jan 2001) $'
12
 * '$Revision: 669 $'
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   group = null;
67
   private Thread   xmlIndex;
68
   private boolean endDocument = false;
69
   private int serverCode = 1;
70

    
71
   private static final int MAXDATACHARS = 4000;
72
   private static final int MAXTITLELEN = 1000;
73

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

    
83
     // Create the stack for keeping track of node context
84
     // if it doesn't already exist
85
     if (!stackCreated) {
86
       nodeStack = new Stack();
87
       nodeIndex = new Vector();
88
       stackCreated = true;
89
     }
90
   }
91
   
92
   public DBSAXHandler(Connection conn, String action, String docid,
93
                       String user, String group, int serverCode)
94
   {
95
     this(conn);
96
     this.action = action;
97
     this.docid = docid;
98
     this.user = user;
99
     this.group = group;
100
     this.xmlIndex = new Thread(this);
101
     this.serverCode = serverCode;
102
   }
103
 
104
   /** Construct an instance of the handler class 
105
    *
106
    * @param conn the JDBC connection to which information is written
107
    * @param action - "INSERT" or "UPDATE"
108
    * @param docid to be inserted or updated into JDBC connection
109
    * @param user the user connected to MetaCat servlet
110
    */
111
   public DBSAXHandler(Connection conn,String action,String docid,
112
                       String user, String group)
113
   {
114
     this(conn);
115
     this.action = action;
116
     this.docid = docid;
117
     this.user = user;
118
     this.group = group;
119
     this.xmlIndex = new Thread(this);
120
     //this.xmlIndex.setPriority(Thread.MIN_PRIORITY);
121
   }
122

    
123
   /** SAX Handler that receives notification of beginning of the document */
124
   public void startDocument() throws SAXException {
125
     MetaCatUtil.debugMessage("start Document");
126

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

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

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

    
155
     DBSAXNode parentNode = null;
156
     DBSAXNode currentNode = null;
157

    
158
     // Get a reference to the parent node for the id
159
     try {
160
       parentNode = (DBSAXNode)nodeStack.peek();
161
     } catch (EmptyStackException e) {
162
       parentNode = null;
163
     }
164

    
165
     // Document representation that points to the root document node
166
     if (atFirstElement) {
167
       atFirstElement = false;
168
       // If no DOCTYPE declaration: docname = root element name 
169
       if (docname == null) {
170
         docname = localName;
171
         doctype = docname;
172
         MetaCatUtil.debugMessage("DOCNAME-a: " + docname);
173
         MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype);
174
       } else if (doctype == null) {
175
         doctype = docname;
176
         MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype);
177
       }
178
       rootNode.writeNodename(docname);
179
       try {
180
         currentDocument = new DocumentImpl(conn, rootNode.getNodeID(), 
181
                                       docname, doctype, docid, action, user, 
182
                                       this.serverCode);
183
       } catch (Exception ane) {
184
         throw (new SAXException("Error with " + action, ane));
185
       }
186
       // not needed any more
187
       //rootNode.writeDocID(currentDocument.getDocID());
188
     }      
189

    
190
     // Create the current node representation
191
     currentNode = new DBSAXNode(conn, localName, parentNode,
192
                                 currentDocument.getRootNodeID(),docid,
193
                                 currentDocument.getDoctype());
194
                               
195
     // Add all of the attributes
196
     for (int i=0; i<atts.getLength(); i++) {
197
       currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i), docid);
198
     }      
199

    
200
     // Add the node to the stack, so that any text data can be 
201
     // added as it is encountered
202
     nodeStack.push(currentNode);
203
     // Add the node to the vector used by thread for writing XML Index
204
     nodeIndex.addElement(currentNode);
205

    
206
  }
207
  
208
  // The run method of xmlIndex thread. It writes XML Index for the document.
209
  public void run () {
210
    DBSAXNode currNode = null;
211
    DBSAXNode prevNode = null;
212
    Connection dbconn = null;
213
    String doctype = currentDocument.getDoctype();
214
    int step = 0;
215
    int counter = 0;
216

    
217
    try {
218
      // Opening separate db connection for writing XML Index
219
      MetaCatUtil util = new MetaCatUtil();
220
      dbconn = util.openDBConnection();
221
      dbconn.setAutoCommit(false);
222

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

    
261
    } catch (Exception e) {
262
      try {
263
        dbconn.rollback();
264
        dbconn.close();
265
      } catch (SQLException sqle) {}
266
      System.out.println("Error writing XML Index. " + e.getMessage()); 
267
    }      
268
  }
269

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

    
294
       // Write the content of the node to the database
295
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
296
     }
297

    
298
     // write the title of document if there are tag <title>
299
     if ( currentNode.getTagName().equals("title") ) {
300
       if ( leftover > MAXTITLELEN ) 
301
         currentDocument.setTitle(new String(cbuf, start, MAXTITLELEN));
302
       else
303
         currentDocument.setTitle(new String(cbuf, start, leftover));
304
     }
305
   }
306

    
307
   /** 
308
    * SAX Handler that is called for each XML text node that is
309
    * Ignorable white space
310
    */
311
   public void ignorableWhitespace(char[] cbuf, int start, int len)
312
               throws SAXException {
313
     // When validation is turned "on", white spaces are reported here
314
     // When validation is turned "off" white spaces are not reported here,
315
     // but through characters() callback
316
     MetaCatUtil.debugMessage("IGNORABLEWHITESPACE");
317
     //System.out.println("Whitespace:" + len + "x" + new String(cbuf, start, len) + "x");
318

    
319
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
320
     String data = null;
321
     int leftover = len;
322
     int offset = start;
323
     boolean moredata = true;
324
     
325
     // This loop deals with the case where there are more characters 
326
     // than can fit in a single database text field (limit is 
327
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
328
     // write a series of nodes that are MAXDATACHARS long, and then the
329
     // final node contains the remainder
330
     while (moredata) {
331
       if (leftover > MAXDATACHARS) {
332
         data = new String(cbuf, offset, MAXDATACHARS);
333
         leftover -= MAXDATACHARS;
334
         offset += MAXDATACHARS;
335
       } else {
336
         data = new String(cbuf, offset, leftover);
337
         moredata = false;
338
       }
339

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

    
345
   /** 
346
    * SAX Handler called once for each processing instruction found: 
347
    * node that PI may occur before or after the root element.
348
    */
349
   public void processingInstruction(String target, String data) 
350
          throws SAXException {
351
     MetaCatUtil.debugMessage("PI");
352
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
353
     currentNode.writeChildNodeToDB("PI", target, data, docid);
354
   }
355

    
356
   /** SAX Handler that is called at the end of each XML element */
357
   public void endElement(String uri, String localName,
358
                          String qName) throws SAXException {
359
     MetaCatUtil.debugMessage("End ELEMENT " + localName);
360

    
361
     // Get the node from the stack
362
     DBSAXNode currentNode = (DBSAXNode)nodeStack.pop();
363
   }
364

    
365
   //
366
   // the next section implements the LexicalHandler interface
367
   //
368

    
369
   /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
370
   public void startDTD(String name, String publicId, String systemId) 
371
               throws SAXException {
372
     docname = name;
373
     doctype = publicId;
374
     systemid = systemId;
375

    
376
     MetaCatUtil.debugMessage("Start DTD");
377
     MetaCatUtil.debugMessage("DOCNAME: " + docname);
378
     MetaCatUtil.debugMessage("DOCTYPE: " + doctype);
379
     MetaCatUtil.debugMessage("  SYSID: " + systemid);
380
   }
381

    
382
   /** 
383
    * SAX Handler that receives notification of end of DTD 
384
    */
385
   public void endDTD() throws SAXException {
386
     MetaCatUtil.debugMessage("end DTD");
387
   }
388

    
389
   /** 
390
    * SAX Handler that receives notification of comments in the DTD
391
    */
392
   public void comment(char[] ch, int start, int length) throws SAXException {
393
     MetaCatUtil.debugMessage("COMMENT");
394
     if ( !processingDTD ) {
395
       DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
396
       currentNode.writeChildNodeToDB("COMMENT", null, new String(ch), docid);
397
     }
398
   }
399

    
400
   /** 
401
    * SAX Handler that receives notification of the start of CDATA sections
402
    */
403
   public void startCDATA() throws SAXException {
404
     MetaCatUtil.debugMessage("start CDATA");
405
   }
406

    
407
   /** 
408
    * SAX Handler that receives notification of the end of CDATA sections
409
    */
410
   public void endCDATA() throws SAXException {
411
     MetaCatUtil.debugMessage("end CDATA");
412
   }
413

    
414
   /** 
415
    * SAX Handler that receives notification of the start of entities
416
    */
417
   public void startEntity(String name) throws SAXException {
418
     MetaCatUtil.debugMessage("start ENTITY: " + name);
419
     if (name.equals("[dtd]")) {
420
       processingDTD = true;
421
     }
422
   }
423

    
424
   /** 
425
    * SAX Handler that receives notification of the end of entities
426
    */
427
   public void endEntity(String name) throws SAXException {
428
     MetaCatUtil.debugMessage("end ENTITY: " + name);
429
     if (name.equals("[dtd]")) {
430
       processingDTD = false;
431
     }
432
   }
433

    
434
   /** 
435
    * SAX Handler that receives notification of element declarations
436
    */
437
   public void elementDecl(String name, String model)
438
                        throws org.xml.sax.SAXException {
439
     MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model);
440
   }
441

    
442
   /** 
443
    * SAX Handler that receives notification of attribute declarations
444
    */
445
   public void attributeDecl(String eName, String aName,
446
                        String type, String valueDefault, String value)
447
                        throws org.xml.sax.SAXException {
448
     MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " 
449
                        + aName + " " + type + " " + valueDefault + " "
450
                        + value);
451
   }
452

    
453
   /** 
454
    * SAX Handler that receives notification of internal entity declarations
455
    */
456
   public void internalEntityDecl(String name, String value)
457
                        throws org.xml.sax.SAXException {
458
     MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value);
459
   }
460

    
461
   /** 
462
    * SAX Handler that receives notification of external entity declarations
463
    */
464
   public void externalEntityDecl(String name, String publicId,
465
                        String systemId)
466
                        throws org.xml.sax.SAXException {
467
     MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId 
468
                              + " " + systemId);
469
   }
470

    
471
   //
472
   // the next section implements the ErrorHandler interface
473
   //
474

    
475
   /** 
476
    * SAX Handler that receives notification of fatal parsing errors
477
    */
478
   public void fatalError(SAXParseException exception) throws SAXException {
479
     MetaCatUtil.debugMessage("FATALERROR");
480
     throw (new SAXException("Fatal processing error.", exception));
481
   }
482

    
483
   /** 
484
    * SAX Handler that receives notification of recoverable parsing errors
485
    */
486
   public void error(SAXParseException exception) throws SAXException {
487
     MetaCatUtil.debugMessage("ERROR");
488
     throw (new SAXException("Processing error.", exception));
489
   }
490

    
491
   /** 
492
    * SAX Handler that receives notification of warnings
493
    */
494
   public void warning(SAXParseException exception) throws SAXException {
495
     MetaCatUtil.debugMessage("WARNING");
496
     throw (new SAXException("Warning.", exception));
497
   }
498

    
499
   // 
500
   // Helper, getter and setter methods
501
   //
502
   
503
   /**
504
    * get the document name
505
    */
506
   public String getDocname() {
507
     return docname;
508
   }
509

    
510
   /**
511
    * get the document processing state
512
    */
513
   public boolean processingDTD() {
514
     return processingDTD;
515
   }
516
}
(15-15/43)