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: 2000-10-03 14:23:59 -0700 (Tue, 03 Oct 2000) $'
12
 * '$Revision: 486 $'
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
    int step = 0;
181
    int counter = 0;
182

    
183
    try {
184
      // Opening separate db connection for writing XML Index
185
      MetaCatUtil util = new MetaCatUtil();
186
      Connection conn = util.getConnection();
187
      conn.setAutoCommit(false);
188

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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