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: 2000-11-06 10:38:17 -0800 (Mon, 06 Nov 2000) $'
12
 * '$Revision: 513 $'
13
 */
14

    
15
package edu.ucsb.nceas.metacat;
16

    
17
import java.sql.*;
18
import java.util.Stack;
19
import java.util.Vector;
20
import java.util.Enumeration;
21
import java.util.EmptyStackException;
22

    
23
import org.xml.sax.Attributes;
24
import org.xml.sax.SAXException;
25
import org.xml.sax.SAXParseException;
26
import org.xml.sax.ext.DeclHandler;
27
import org.xml.sax.ext.LexicalHandler;
28
import org.xml.sax.helpers.DefaultHandler;
29

    
30
/** 
31
 * A database aware Class implementing callback bethods for the SAX parser to
32
 * call when processing the XML stream and generating events
33
 */
34
public class DBSAXHandler extends DefaultHandler 
35
                          implements LexicalHandler, DeclHandler, Runnable {
36

    
37
   private boolean	atFirstElement;
38
   private boolean	processingDTD;
39
   private String 	docname = null;
40
   private String 	doctype;
41
   private String 	systemid;
42
   private boolean 	stackCreated = false;
43
   private Stack 	  nodeStack;
44
   private Vector   nodeIndex;
45
   private Connection	  conn = null;
46
   private DocumentImpl currentDocument;
47
   private DBSAXNode    rootNode;
48
   private String   action = null;
49
   private String   docid = null;
50
   private String   user = null;
51
   private Thread   xmlIndex;
52
   private boolean endDocument = false;
53

    
54
   private static final int MAXDATACHARS = 4000;
55
   private static final int MAXTITLELEN = 1000;
56

    
57
   /** Construct an instance of the handler class 
58
    *
59
    * @param conn the JDBC connection to which information is written
60
    */
61
   public DBSAXHandler(Connection conn) {
62
     this.conn = conn;
63
     this.atFirstElement = true;
64
     this.processingDTD = false;
65

    
66
     // Create the stack for keeping track of node context
67
     // if it doesn't already exist
68
     if (!stackCreated) {
69
       nodeStack = new Stack();
70
       nodeIndex = new Vector();
71
       stackCreated = true;
72
     }
73
   }
74
 
75
   /** Construct an instance of the handler class 
76
    *
77
    * @param conn the JDBC connection to which information is written
78
    * @param action - "INSERT" or "UPDATE"
79
    * @param docid to be inserted or updated into JDBC connection
80
    * @param user the user connected to MetaCat servlet
81
    */
82
   public DBSAXHandler(Connection conn,String action,String docid,String user)
83
   {
84
     this(conn);
85
     this.action = action;
86
     this.docid = docid;
87
     this.user = user;
88
     this.xmlIndex = new Thread(this);
89
     //this.xmlIndex.setPriority(Thread.MIN_PRIORITY);
90
   }
91

    
92
   /** SAX Handler that receives notification of beginning of the document */
93
   public void startDocument() throws SAXException {
94
     MetaCatUtil.debugMessage("start Document");
95

    
96
     // Create the document node representation as root
97
     rootNode = new DBSAXNode(conn, this.docid);
98
     // Add the node to the stack, so that any text data can be 
99
     // added as it is encountered
100
     nodeStack.push(rootNode);
101
   }
102

    
103
   /** SAX Handler that receives notification of end of the document */
104
   public void endDocument() throws SAXException {
105
     MetaCatUtil.debugMessage("end Document");
106
     // Starting new thread for writing XML Index.
107
     // It calls the run method of the thread.
108
     try {
109
       xmlIndex.start();
110
     } catch (NullPointerException e) {
111
       xmlIndex = null;
112
       throw new 
113
       SAXException("Problem with starting thread for writing XML Index. " +
114
                    e.getMessage());
115
     }
116
   }
117

    
118
   /** SAX Handler that is called at the start of each XML element */
119
   public void startElement(String uri, String localName,
120
                            String qName, Attributes atts) 
121
               throws SAXException {
122
     MetaCatUtil.debugMessage("Start ELEMENT " + localName);
123

    
124
     DBSAXNode parentNode = null;
125
     DBSAXNode currentNode = null;
126

    
127
     // Get a reference to the parent node for the id
128
     try {
129
       parentNode = (DBSAXNode)nodeStack.peek();
130
     } catch (EmptyStackException e) {
131
       parentNode = null;
132
     }
133

    
134
     // Document representation that points to the root document node
135
     if (atFirstElement) {
136
       atFirstElement = false;
137
       // If no DOCTYPE declaration: docname = root element name 
138
       if (docname == null) {
139
         docname = localName;
140
         doctype = docname;
141
         MetaCatUtil.debugMessage("DOCNAME-a: " + docname);
142
         MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype);
143
       } else if (doctype == null) {
144
         doctype = docname;
145
         MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype);
146
       }
147
       rootNode.writeNodename(docname);
148
       try {
149
         currentDocument = new DocumentImpl(conn, rootNode.getNodeID(), 
150
                                       docname, doctype, docid, action, user);
151
       } catch (Exception ane) {
152
         throw (new SAXException("Error with " + action, ane));
153
       }
154
       // not needed any more
155
       //rootNode.writeDocID(currentDocument.getDocID());
156
     }      
157

    
158
     // Create the current node representation
159
     currentNode = new DBSAXNode(conn, localName, parentNode,
160
                                 currentDocument.getRootNodeID(),docid,
161
                                 currentDocument.getDoctype());
162
                               
163
     // Add all of the attributes
164
     for (int i=0; i<atts.getLength(); i++) {
165
       currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i), docid);
166
     }      
167

    
168
     // Add the node to the stack, so that any text data can be 
169
     // added as it is encountered
170
     nodeStack.push(currentNode);
171
     // Add the node to the vector used by thread for writing XML Index
172
     nodeIndex.addElement(currentNode);
173

    
174
  }
175
  
176
  // The run method of xmlIndex thread. It writes XML Index for the document.
177
  public void run () {
178
    DBSAXNode currNode = null;
179
    DBSAXNode prevNode = null;
180
    Connection dbconn = null;
181
    int step = 0;
182
    int counter = 0;
183

    
184
    try {
185
      // Opening separate db connection for writing XML Index
186
      MetaCatUtil util = new MetaCatUtil();
187
      dbconn = util.openDBConnection();
188
      dbconn.setAutoCommit(false);
189

    
190
      // Going through the elements of the document and writing its Index
191
      Enumeration nodes = nodeIndex.elements();
192
      while ( nodes.hasMoreElements() ) {
193
        currNode = (DBSAXNode)nodes.nextElement();
194
        currNode.updateNodeIndex(dbconn, docid, currentDocument.getDoctype());
195
      }
196
    
197
      dbconn.commit();
198
      
199
      //if this is a package file then write the package info to 
200
      //the xml_relation table. relationHandler checks to see
201
      //if it is a package file so you don't have to do it here.
202
      DocumentImpl xmldoc = new DocumentImpl(dbconn, docid);
203
      relationHandler rth = new relationHandler(xmldoc, dbconn);
204
      
205
      dbconn.close();
206

    
207
    } catch (Exception e) {
208
      try {
209
        dbconn.rollback();
210
        dbconn.close();
211
      } catch (SQLException sqle) {}
212
      System.out.println("Error writing XML Index. " + e.getMessage()); 
213
    }      
214
  }
215

    
216
  /** SAX Handler that is called for each XML text node */
217
  public void characters(char[] cbuf, int start, int len) throws SAXException {
218
     MetaCatUtil.debugMessage("CHARACTERS");
219
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
220
     String data = null;
221
     int leftover = len;
222
     int offset = start;
223
     boolean moredata = true;
224
    
225
     // This loop deals with the case where there are more characters 
226
     // than can fit in a single database text field (limit is 
227
     // MAXDATACHARS).  If the text to be inserted exceeds MAXDATACHARS,
228
     // write a series of nodes that are MAXDATACHARS long, and then the
229
     // final node contains the remainder
230
     while (moredata) {
231
       if (leftover > MAXDATACHARS) {
232
         data = new String(cbuf, offset, MAXDATACHARS);
233
         leftover -= MAXDATACHARS;
234
         offset += MAXDATACHARS;
235
       } else {
236
         data = new String(cbuf, offset, leftover);
237
         moredata = false;
238
       }
239

    
240
       // Write the content of the node to the database
241
       currentNode.writeChildNodeToDB("TEXT", null, data, docid);
242
     }
243

    
244
     // write the title of document if there are tag <title>
245
     if ( currentNode.getTagName().equals("title") ) {
246
       if ( leftover > MAXTITLELEN ) 
247
         currentDocument.setTitle(new String(cbuf, start, MAXTITLELEN));
248
       else
249
         currentDocument.setTitle(new String(cbuf, start, leftover));
250
     }
251
   }
252

    
253
   /** 
254
    * SAX Handler that is called for each XML text node that is Ignorable
255
    * white space
256
    */
257
   public void ignorableWhitespace(char[] cbuf, int start, int len) {
258
     MetaCatUtil.debugMessage("IGNORABLEWHITESPACE");
259
   }
260

    
261
   /** 
262
    * SAX Handler called once for each processing instruction found: 
263
    * node that PI may occur before or after the root element.
264
    */
265
   public void processingInstruction(String target, String data) 
266
          throws SAXException {
267
     MetaCatUtil.debugMessage("PI");
268
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
269
     currentNode.writeChildNodeToDB("PI", target, data, docid);
270
   }
271

    
272
   /** SAX Handler that is called at the end of each XML element */
273
   public void endElement(String uri, String localName,
274
                          String qName) throws SAXException {
275
     MetaCatUtil.debugMessage("End ELEMENT " + localName);
276

    
277
     // Get the node from the stack
278
     DBSAXNode currentNode = (DBSAXNode)nodeStack.pop();
279
   }
280

    
281
   //
282
   // the next section implements the LexicalHandler interface
283
   //
284

    
285
   /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
286
   public void startDTD(String name, String publicId, String systemId) 
287
               throws SAXException {
288
     docname = name;
289
     doctype = publicId;
290
     systemid = systemId;
291

    
292
     MetaCatUtil.debugMessage("Start DTD");
293
     MetaCatUtil.debugMessage("DOCNAME: " + docname);
294
     MetaCatUtil.debugMessage("DOCTYPE: " + doctype);
295
     MetaCatUtil.debugMessage("  SYSID: " + systemid);
296
   }
297

    
298
   /** 
299
    * SAX Handler that receives notification of end of DTD 
300
    */
301
   public void endDTD() throws SAXException {
302
     MetaCatUtil.debugMessage("end DTD");
303
   }
304

    
305
   /** 
306
    * SAX Handler that receives notification of comments in the DTD
307
    */
308
   public void comment(char[] ch, int start, int length) throws SAXException {
309
     MetaCatUtil.debugMessage("COMMENT");
310
     DBSAXNode currentNode = (DBSAXNode)nodeStack.peek();
311
     currentNode.writeChildNodeToDB("COMMENT", null, new String(ch), docid);
312
   }
313

    
314
   /** 
315
    * SAX Handler that receives notification of the start of CDATA sections
316
    */
317
   public void startCDATA() throws SAXException {
318
     MetaCatUtil.debugMessage("start CDATA");
319
   }
320

    
321
   /** 
322
    * SAX Handler that receives notification of the end of CDATA sections
323
    */
324
   public void endCDATA() throws SAXException {
325
     MetaCatUtil.debugMessage("end CDATA");
326
   }
327

    
328
   /** 
329
    * SAX Handler that receives notification of the start of entities
330
    */
331
   public void startEntity(String name) throws SAXException {
332
     MetaCatUtil.debugMessage("start ENTITY: " + name);
333
     if (name.equals("[dtd]")) {
334
       processingDTD = true;
335
     }
336
   }
337

    
338
   /** 
339
    * SAX Handler that receives notification of the end of entities
340
    */
341
   public void endEntity(String name) throws SAXException {
342
     MetaCatUtil.debugMessage("end ENTITY: " + name);
343
     if (name.equals("[dtd]")) {
344
       processingDTD = false;
345
     }
346
   }
347

    
348
   /** 
349
    * SAX Handler that receives notification of element declarations
350
    */
351
   public void elementDecl(String name, String model)
352
                        throws org.xml.sax.SAXException {
353
     MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model);
354
   }
355

    
356
   /** 
357
    * SAX Handler that receives notification of attribute declarations
358
    */
359
   public void attributeDecl(String eName, String aName,
360
                        String type, String valueDefault, String value)
361
                        throws org.xml.sax.SAXException {
362
     MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " 
363
                        + aName + " " + type + " " + valueDefault + " "
364
                        + value);
365
   }
366

    
367
   /** 
368
    * SAX Handler that receives notification of internal entity declarations
369
    */
370
   public void internalEntityDecl(String name, String value)
371
                        throws org.xml.sax.SAXException {
372
     MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value);
373
   }
374

    
375
   /** 
376
    * SAX Handler that receives notification of external entity declarations
377
    */
378
   public void externalEntityDecl(String name, String publicId,
379
                        String systemId)
380
                        throws org.xml.sax.SAXException {
381
     MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId 
382
                              + " " + systemId);
383
   }
384

    
385
   //
386
   // the next section implements the ErrorHandler interface
387
   //
388

    
389
   /** 
390
    * SAX Handler that receives notification of fatal parsing errors
391
    */
392
   public void fatalError(SAXParseException exception) throws SAXException {
393
     MetaCatUtil.debugMessage("FATALERROR");
394
     throw (new SAXException("Fatal processing error.", exception));
395
   }
396

    
397
   /** 
398
    * SAX Handler that receives notification of recoverable parsing errors
399
    */
400
   public void error(SAXParseException exception) throws SAXException {
401
     MetaCatUtil.debugMessage("ERROR");
402
   }
403

    
404
   /** 
405
    * SAX Handler that receives notification of warnings
406
    */
407
   public void warning(SAXParseException exception) throws SAXException {
408
     MetaCatUtil.debugMessage("FATALERROR");
409
   }
410

    
411
   // 
412
   // Helper, getter and setter methods
413
   //
414
   
415
   /**
416
    * get the document name
417
    */
418
   public String getDocname() {
419
     return docname;
420
   }
421

    
422
   /**
423
    * get the document processing state
424
    */
425
   public boolean processingDTD() {
426
     return processingDTD;
427
   }
428
}
(13-13/35)