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
 *
9
 *   '$Author: leinfelder $'
10
 *     '$Date: 2011-11-04 14:45:59 -0700 (Fri, 04 Nov 2011) $'
11
 * '$Revision: 6606 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.sql.PreparedStatement;
31
import java.sql.ResultSet;
32
import java.sql.Statement;
33
import java.util.Date;
34
import java.util.EmptyStackException;
35
import java.util.Enumeration;
36
import java.util.Hashtable;
37
import java.util.Stack;
38
import java.util.Vector;
39

    
40
import edu.ucsb.nceas.metacat.database.DBConnection;
41
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
42
import edu.ucsb.nceas.metacat.properties.PropertyService;
43
import edu.ucsb.nceas.metacat.service.XMLSchema;
44
import edu.ucsb.nceas.metacat.util.MetacatUtil;
45
import edu.ucsb.nceas.morpho.datapackage.Triple;
46
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
47
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
48
import edu.ucsb.nceas.utilities.StringUtil;
49

    
50
import org.apache.log4j.Logger;
51
import org.xml.sax.Attributes;
52
import org.xml.sax.SAXException;
53
import org.xml.sax.SAXParseException;
54
import org.xml.sax.ext.DeclHandler;
55
import org.xml.sax.ext.LexicalHandler;
56
import org.xml.sax.helpers.DefaultHandler;
57

    
58
/**
59
 * A database aware Class implementing callback bethods for the SAX parser to
60
 * call when processing the XML stream and generating events.
61
 */
62
public class DBSAXHandler extends DefaultHandler implements LexicalHandler,
63
        DeclHandler
64
{
65

    
66
    protected boolean atFirstElement;
67

    
68
    protected boolean processingDTD;
69

    
70
    protected String docname = null;
71

    
72
    protected String doctype;
73
    
74
    protected String catalogid = null;
75

    
76
    protected String systemid;
77

    
78
    private boolean stackCreated = false;
79

    
80
    protected Stack<DBSAXNode> nodeStack;
81

    
82
    protected Vector<DBSAXNode> nodeIndex;
83

    
84
    protected DBConnection connection = null;
85

    
86
    protected DocumentImpl currentDocument;
87
    
88
    protected Date createDate = null;
89
    
90
    protected Date updateDate = null;
91

    
92
    protected DBSAXNode rootNode;
93

    
94
    protected String action = null;
95

    
96
    protected String docid = null;
97

    
98
    protected String revision = null;
99

    
100
    protected String user = null;
101

    
102
    protected String[] groups = null;
103

    
104
    protected String pub = null;
105
    
106
	protected String encoding = null;
107

    
108
//    private boolean endDocument = false;
109

    
110
    protected int serverCode = 1;
111

    
112
    protected Hashtable<String,String> namespaces = new Hashtable<String,String>();
113

    
114
    protected boolean hitTextNode = false; // a flag to hit text node
115

    
116
    // a buffer to keep all text nodes for same element
117
    // it is for if element was split
118
    protected StringBuffer textBuffer = new StringBuffer();
119

    
120
//    protected Stack textBufferStack = new Stack();
121

    
122
    public static final int MAXDATACHARS = 4000;
123

    
124
    //protected static final int MAXDATACHARS = 50;
125

    
126
    // methods writeChildNodeToDB, setAttribute, setNamespace,
127
    // writeTextForDBSAXNode will increase endNodeId.
128
    protected long endNodeId = -1; // The end node id for a substree
129
    // DOCTITLE attr cleared from the db
130
    //   private static final int MAXTITLELEN = 1000;
131
    
132
    private boolean isRevisionDoc  = false;
133
    
134
    protected Vector<XMLSchema> schemaList = new Vector<XMLSchema>();
135

    
136
    //HandlerTriple stuff
137
    TripleCollection tripleList = new TripleCollection();
138

    
139
    Triple currentTriple = new Triple();
140

    
141
    boolean startParseTriple = false;
142

    
143
    boolean hasTriple = false;
144

    
145
    public static final String ECOGRID = "ecogrid://";
146

    
147
    private Logger logMetacat = Logger.getLogger(DBSAXHandler.class);
148

    
149
    /**
150
     * Construct an instance of the handler class
151
     *
152
     * @param conn the JDBC connection to which information is written
153
     */
154
    private DBSAXHandler(DBConnection conn, Date createDate, Date updateDate)
155
    {
156
        this.connection = conn;
157
        this.atFirstElement = true;
158
        this.processingDTD = false;
159
        this.createDate = createDate;
160
        this.updateDate = updateDate;
161

    
162
        // Create the stack for keeping track of node context
163
        // if it doesn't already exist
164
        if (!stackCreated) {
165
            nodeStack = new Stack<DBSAXNode>();
166
            nodeIndex = new Vector<DBSAXNode>();
167
            stackCreated = true;
168
        }
169
    }
170

    
171
    /**
172
     * Construct an instance of the handler class
173
     *
174
     * @param conn the JDBC connection to which information is written
175
     * @param action - "INSERT" or "UPDATE"
176
     * @param docid to be inserted or updated into JDBC connection
177
     * @param user the user connected to MetaCat servlet and owns the document
178
     * @param groups the groups to which user belongs
179
     * @param pub flag for public "read" access on document
180
     * @param serverCode the serverid from xml_replication on which this
181
     *            document resides.
182
     *
183
     */
184
/* TODO excise this constructor because not used anywhere in project
185
    public DBSAXHandler(DBConnection conn, String action, String docid,
186
            String user, String[] groups, String pub, int serverCode)
187
    {
188
        this(conn);
189
        this.action = action;
190
        this.docid = docid;
191
        this.user = user;
192
        this.groups = groups;
193
        this.pub = pub;
194
        this.serverCode = serverCode;
195
        this.xmlIndex = new Thread(this);
196
    }
197
*/
198
    /**
199
     * Construct an instance of the handler class In this constructor, user can
200
     * specify the version need to upadate
201
     *
202
     * @param conn the JDBC connection to which information is written
203
     * @param action - "INSERT" or "UPDATE"
204
     * @param docid to be inserted or updated into JDBC connection
205
     * @param revision, the user specified the revision need to be update
206
     * @param user the user connected to MetaCat servlet and owns the document
207
     * @param groups the groups to which user belongs
208
     * @param pub flag for public "read" access on document
209
     * @param serverCode the serverid from xml_replication on which this
210
     *            document resides.
211
     *
212
     */
213
    public DBSAXHandler(DBConnection conn, String action, String docid,
214
            String revision, String user, String[] groups, String pub,
215
            int serverCode, Date createDate, Date updateDate)
216
    {
217
        this(conn, createDate, updateDate);
218
        this.action = action;
219
        this.docid = docid;
220
        this.revision = revision;
221
        this.user = user;
222
        this.groups = groups;
223
        this.pub = pub;
224
        this.serverCode = serverCode;
225
    }
226

    
227
    /** SAX Handler that receives notification of beginning of the document */
228
    public void startDocument() throws SAXException
229
    {
230
        logMetacat.debug("DBSaxHandler.startDocument - starting document");
231

    
232
        // Create the document node representation as root
233
        rootNode = new DBSAXNode(connection, this.docid);
234
        // Add the node to the stack, so that any text data can be
235
        // added as it is encountered
236
        nodeStack.push(rootNode);
237
    }
238

    
239
    /** SAX Handler that receives notification of end of the document */
240
	public void endDocument() throws SAXException {
241
		logMetacat.debug("DBSaxHandler.endDocument - ending document");
242
		// Starting new thread for writing XML Index.
243
		// It calls the run method of the thread.
244

    
245
		try {
246
			// if it is data package insert triple into relation table;
247
			if (doctype != null
248
					&& MetacatUtil.getOptionList(
249
							PropertyService.getProperty("xml.packagedoctype")).contains(
250
							doctype) && hasTriple && !isRevisionDoc) {
251

    
252
				// initial handler and write into relation db only for
253
				// xml-documents
254
				if (!isRevisionDoc) {
255
					RelationHandler handler = new RelationHandler(docid, doctype,
256
							connection, tripleList);
257
				}
258
			}
259
		} catch (Exception e) {
260
			logMetacat.error("DBSaxHandler.endDocument - Failed to write triples into relation table"
261
					+ e.getMessage());
262
			throw new SAXException("Failed to write triples into relation table "
263
					+ e.getMessage());
264
		}
265
		
266
		// If we get here, the document and schema parsed okay.  If there are
267
		// any schemas in the schema list, they are new and need to be registered.
268
    	for (XMLSchema xmlSchema : schemaList) {
269
    		String externalFileUri = xmlSchema.getExternalFileUri();
270
    		String fileNamespace = xmlSchema.getFileNamespace();
271
    		SchemaLocationResolver resolver = 
272
    			new SchemaLocationResolver(fileNamespace, externalFileUri);
273
    		resolver.resolveNameSpace();
274
    	}
275
	}
276

    
277
    /** SAX Handler that is called at the start of Namespace */
278
    public void startPrefixMapping(String prefix, String uri)
279
            throws SAXException
280
    {
281
        logMetacat.debug("DBSaxHandler.startPrefixMapping - Starting namespace");
282

    
283
        namespaces.put(prefix, uri);
284
    }
285

    
286
    /** SAX Handler that is called at the start of each XML element */
287
    public void startElement(String uri, String localName, String qName,
288
            Attributes atts) throws SAXException
289
    {
290
        // for element <eml:eml...> qname is "eml:eml", local name is "eml"
291
        // for element <acl....> both qname and local name is "eml"
292
        // uri is namespace
293
        logMetacat.debug("DBSaxHandler.startElement - Start ELEMENT(qName) " + qName);
294
        logMetacat.debug("DBSaxHandler.startElement - Start ELEMENT(localName) " + localName);
295
        logMetacat.debug("DBSaxHandler.startElement - Start ELEMENT(uri) " + uri);
296

    
297
        DBSAXNode parentNode = null;
298
        DBSAXNode currentNode = null;
299

    
300
        // Get a reference to the parent node for the id
301
        try {
302
            
303
            parentNode = (DBSAXNode) nodeStack.peek();
304
        } catch (EmptyStackException e) {
305
            parentNode = null;
306
        }
307

    
308
        // If hit a text node, we need write this text for current's parent
309
        // node This will happen if the element is mixed
310
        if (hitTextNode && parentNode != null) {
311
            // write the textbuffer into db for parent node.
312
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, parentNode);
313
            // rest hitTextNode
314
            hitTextNode = false;
315
            // reset textbuffer
316
            textBuffer = null;
317
            textBuffer = new StringBuffer();
318
           
319
        }
320
        
321
        // Document representation that points to the root document node
322
        if (atFirstElement) {
323
            atFirstElement = false;
324
            // If no DOCTYPE declaration: docname = root element
325
            // doctype = root element name or name space
326
            if (docname == null) {
327
                docname = localName;
328
                // if uri isn't null doctype = uri(namespace)
329
                // otherwise root element
330
                if (uri != null && !(uri.trim()).equals("")) {
331
                    doctype = uri;
332
                } else {
333
                    doctype = docname;
334
                }
335
                logMetacat.debug("DBSaxHandler.startElement - DOCNAME-a: " + docname);
336
                logMetacat.debug("DBSaxHandler.startElement - DOCTYPE-a: " + doctype);
337
            } else if (doctype == null) {
338
                // because docname is not null and it is declared in dtd
339
                // so could not be in schema, no namespace
340
                doctype = docname;
341
                logMetacat.debug("DBSaxHandler.startElement - DOCTYPE-b: " + doctype);
342
            }
343
           
344
            rootNode.writeNodename(docname);
345
          
346
            try {
347
                // for validated XML Documents store a reference to XML DB
348
                // Catalog
349
                // Because this is select statement and it needn't to roll back
350
                // if
351
                // insert document action failed.
352
                // In order to decrease DBConnection usage count, we get a new
353
                // dbconnection from pool
354
               
355
                DBConnection dbConn = null;
356
                int serialNumber = -1;
357
               
358
                if (systemid != null) {
359
                    try {
360
                        // Get dbconnection
361
                        dbConn = DBConnectionPool
362
                                .getDBConnection("DBSAXHandler.startElement");
363
                        serialNumber = dbConn.getCheckOutSerialNumber();
364

    
365
                        String sql = "SELECT catalog_id FROM xml_catalog "
366
                            + "WHERE entry_type = 'DTD' "
367
                            + "AND public_id = ?";
368
                        	
369
                        PreparedStatement pstmt = dbConn.prepareStatement(sql);
370
                        pstmt.setString(1, doctype);
371
                        ResultSet rs = pstmt.executeQuery();
372
                        boolean hasRow = rs.next();
373
                        if (hasRow) {
374
                            catalogid = rs.getString(1);
375
                        }
376
                        pstmt.close();
377
                    }//try
378
                    finally {
379
                        // Return dbconnection
380
                        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
381
                    }//finally
382
                }
383

    
384
                //create documentImpl object by the constructor which can
385
                // specify
386
                //the revision
387
              
388
                if (!isRevisionDoc)
389
                {
390
                  currentDocument = new DocumentImpl(connection, rootNode
391
                        .getNodeID(), docname, doctype, docid, revision,
392
                        action, user, this.pub, catalogid, this.serverCode, 
393
                        createDate, updateDate);
394
                }               
395
            } catch (Exception ane) {
396
                ane.printStackTrace(System.out);
397
                ane.printStackTrace(System.err);
398
                throw (new SAXException("Error in DBSaxHandler.startElement for action "
399
                        + action + " : " + ane.getMessage(), ane));
400
            }
401
        }
402

    
403
        // Create the current node representation
404
        currentNode = new DBSAXNode(connection, qName, localName,
405
                parentNode, rootNode.getNodeID(), docid, doctype);
406

    
407
        // Add all of the namespaces
408
        String prefix;
409
        String nsuri;
410
        Enumeration<String> prefixes = namespaces.keys();
411
        while (prefixes.hasMoreElements()) {
412
            prefix = (String) prefixes.nextElement();
413
            nsuri = (String) namespaces.get(prefix);
414
            currentNode.setNamespace(prefix, nsuri, docid);
415
        }
416
        namespaces = null;
417
        namespaces = new Hashtable<String,String>();
418

    
419
        // Add all of the attributes
420
        for (int i = 0; i < atts.getLength(); i++) {
421
            String attributeName = atts.getQName(i);
422
            String attributeValue = atts.getValue(i);
423
            endNodeId = currentNode.setAttribute(attributeName, attributeValue,
424
                    docid);
425

    
426
            // To handle name space and schema location if the attribute name
427
            // is xsi:schemaLocation. If the name space is in not in catalog 
428
            // table it will be registered.
429
            if (attributeName != null
430
                    && attributeName
431
                            .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
432
            	// These schemas will be registered in the end endDocument() method
433
            	// assuming parsing is successful.
434
        		// each namespace could have several schema locations.  parsedUri will
435
        		// hold a list of uri and files.
436
            	attributeValue = StringUtil.replaceTabsNewLines(attributeValue);
437
            	attributeValue = StringUtil.replaceDuplicateSpaces(attributeValue);
438
        		Vector<String> parsedUri = StringUtil.toVector(attributeValue, ' ');
439
        		for (int j = 0; j < parsedUri.size(); j = j + 2 ) {
440
        			if (j + 1 >= parsedUri.size()) {
441
        				throw new SAXException("Odd number of elements found when parsing schema location: " + 	
442
        						attributeValue + ". There should be an even number of uri/files in location.");
443
        			}
444
        			XMLSchema xmlSchema = 
445
        				new XMLSchema(parsedUri.get(j), parsedUri.get(j + 1));
446
        			schemaList.add(xmlSchema);
447
        		}
448
            }
449
        }
450

    
451
        // Add the node to the stack, so that any text data can be
452
		// added as it is encountered
453
		nodeStack.push(currentNode);
454
		// Add the node to the vector used by thread for writing XML Index
455
		nodeIndex.addElement(currentNode);
456
		// start parsing triple
457
		try {
458
			if (doctype != null
459
					&& MetacatUtil.getOptionList(
460
							PropertyService.getProperty("xml.packagedoctype")).contains(doctype)
461
					&& localName.equals("triple")) {
462
				startParseTriple = true;
463
				hasTriple = true;
464
				currentTriple = new Triple();
465
			}
466
		} catch (PropertyNotFoundException pnfe) {
467
			pnfe.printStackTrace(System.out);
468
			pnfe.printStackTrace(System.err);
469
			throw (new SAXException("Error in DBSaxHandler.startElement for action " + action +
470
			        " : " + pnfe.getMessage(), pnfe));
471
		}
472
	}               
473
    
474

    
475
    /** SAX Handler that is called for each XML text node */
476
    public void characters(char[] cbuf, int start, int len) throws SAXException
477
    {
478
        logMetacat.debug("DBSaxHandler.characters - starting characters");
479
        // buffer all text nodes for same element. This is for if text was split
480
        // into different nodes
481
        textBuffer.append(new String(cbuf, start, len));
482
        // set hittextnode true
483
        hitTextNode = true;
484
        // if text buffer .size is greater than max, write it to db.
485
        // so we can save memory
486
        if (textBuffer.length() > MAXDATACHARS) {
487
            logMetacat.debug("DBSaxHandler.characters - Write text into DB in charaters"
488
                    + " when text buffer size is greater than maxmum number");
489
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
490
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
491
                    currentNode);
492
            textBuffer = null;
493
            textBuffer = new StringBuffer();
494
        }
495
    }
496

    
497
    /**
498
     * SAX Handler that is called for each XML text node that is Ignorable
499
     * white space
500
     */
501
    public void ignorableWhitespace(char[] cbuf, int start, int len)
502
            throws SAXException
503
    {
504
        // When validation is turned "on", white spaces are reported here
505
        // When validation is turned "off" white spaces are not reported here,
506
        // but through characters() callback
507
        logMetacat.debug("DBSaxHandler.ignorableWhitespace - in ignorableWhitespace");
508

    
509
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
510

    
511
            // Write the content of the node to the database
512
            endNodeId = currentNode.writeChildNodeToDB("TEXT", null, new String(cbuf, start, len),
513
                    docid);
514
    }
515

    
516
    /**
517
     * SAX Handler called once for each processing instruction found: node that
518
     * PI may occur before or after the root element.
519
     */
520
    public void processingInstruction(String target, String data)
521
            throws SAXException
522
    {
523
        logMetacat.debug("DBSaxHandler.processingInstruction - in processing instructions");
524
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
525
        endNodeId = currentNode.writeChildNodeToDB("PI", target, data, docid);
526
    }
527

    
528
    /** SAX Handler that is called at the end of each XML element */
529
    public void endElement(String uri, String localName, String qName)
530
            throws SAXException
531
    {
532
        logMetacat.debug("DBSaxHandler.endElement - End element " + qName);
533

    
534
        // write buffered text nodes into db (so no splited)
535
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
536

    
537
        // If before the end element, the parser hit text nodes and store them
538
        // into the buffer, write the buffer to data base. The reason we put
539
        // write database here is for xerces some time split text node
540
        if (hitTextNode) {
541
            logMetacat.debug("DBSaxHandler.endElement - Write text into DB in End Element");
542
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
543
                    currentNode);
544

    
545
            //if it is triple parsing process
546
            if (startParseTriple) {
547

    
548
                String content = textBuffer.toString().trim();
549
                if (localName.equals("subject")) { //get the subject content
550
                    currentTriple.setSubject(content);
551
                } else if (localName.equals("relationship")) { //get the
552
                                                               // relationship
553
                                                               // content
554
                    currentTriple.setRelationship(content);
555
                } else if (localName.equals("object")) { //get the object
556
                                                         // content
557
                    currentTriple.setObject(content);
558
                }
559
            }
560

    
561
        }//if
562

    
563
        //set hitText false
564
        hitTextNode = false;
565
        // reset textbuff
566
        textBuffer = null;
567
        textBuffer = new StringBuffer();
568

    
569
        // Get the node from the stack
570
        currentNode = (DBSAXNode) nodeStack.pop();
571
        //finishing parsing single triple
572
        if (startParseTriple && localName.equals("triple")) {
573
            // add trip to triple collection
574
            tripleList.addTriple(currentTriple);
575
            //rest variable
576
            currentTriple = null;
577
            startParseTriple = false;
578
        }
579
    }
580

    
581
    //
582
    // the next section implements the LexicalHandler interface
583
    //
584

    
585
    /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
586
    public void startDTD(String name, String publicId, String systemId)
587
            throws SAXException
588
    {
589
        docname = name;
590
        doctype = publicId;
591
        systemid = systemId;
592

    
593
        processingDTD = true;
594
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
595
        //create a DTD node and write docname,publicid and system id into db
596
        // we don't put the dtd node into node stack
597
        DBSAXNode dtdNode = new DBSAXNode(connection, name, publicId, systemId,
598
                currentNode, currentNode.getRootNodeID(), docid);
599
        logMetacat.debug("DBSaxHandler.startDTD - Start DTD");
600
        logMetacat.debug("DBSaxHandler.startDTD - Setting processingDTD to true");
601
        logMetacat.debug("DBSaxHandler.startDTD - DOCNAME: " + docname);
602
        logMetacat.debug("DBSaxHandler.startDTD - DOCTYPE: " + doctype);
603
        logMetacat.debug("DBSaxHandler.startDTD - SYSID: " + systemid);
604
    }
605

    
606
    /**
607
     * SAX Handler that receives notification of end of DTD
608
     */
609
    public void endDTD() throws SAXException
610
    {
611

    
612
        processingDTD = false;
613
        logMetacat.debug("DBSaxHandler.endDTD - Setting processingDTD to false");
614
        logMetacat.debug("DBSaxHandler.endDTD - end DTD");
615
    }
616

    
617
    /**
618
     * SAX Handler that receives notification of comments in the DTD
619
     */
620
    public void comment(char[] ch, int start, int length) throws SAXException
621
    {
622
        logMetacat.debug("DBSaxHandler.comment - starting comment");
623
        if (!processingDTD) {
624
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
625
            endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
626
                    new String(ch, start, length), docid);
627
        }
628
    }
629

    
630
    /**
631
     * SAX Handler that receives notification of the start of CDATA sections
632
     */
633
    public void startCDATA() throws SAXException
634
    {
635
        logMetacat.debug("DBSaxHandler.startCDATA - starting CDATA");
636
    }
637

    
638
    /**
639
     * SAX Handler that receives notification of the end of CDATA sections
640
     */
641
    public void endCDATA() throws SAXException
642
    {
643
        logMetacat.debug("DBSaxHandler.endCDATA - end CDATA");
644
    }
645

    
646
    /**
647
     * SAX Handler that receives notification of the start of entities
648
     */
649
    public void startEntity(String name) throws SAXException
650
    {
651
        logMetacat.debug("DBSaxHandler.startEntity - starting entity: " + name);
652
        //System.out.println("start ENTITY: " + name);
653
        if (name.equals("[dtd]")) {
654
            processingDTD = true;
655
        }
656
    }
657

    
658
    /**
659
     * SAX Handler that receives notification of the end of entities
660
     */
661
    public void endEntity(String name) throws SAXException
662
    {
663
        logMetacat.debug("DBSaxHandler.endEntity - ending entity: " + name);
664
        //System.out.println("end ENTITY: " + name);
665
        if (name.equals("[dtd]")) {
666
            processingDTD = false;
667
        }
668
    }
669

    
670
    /**
671
     * SAX Handler that receives notification of element declarations
672
     */
673
    public void elementDecl(String name, String model)
674
            throws org.xml.sax.SAXException
675
    {
676
        //System.out.println("ELEMENTDECL: " + name + " " + model);
677
        logMetacat.debug("DBSaxHandler.elementDecl - element declaration: " + name + " " + model);
678
    }
679

    
680
    /**
681
     * SAX Handler that receives notification of attribute declarations
682
     */
683
    public void attributeDecl(String eName, String aName, String type,
684
            String valueDefault, String value) throws org.xml.sax.SAXException
685
    {
686

    
687
        //System.out.println("ATTRIBUTEDECL: " + eName + " "
688
        //                        + aName + " " + type + " " + valueDefault + " "
689
        //                        + value);
690
        logMetacat.debug("DBSaxHandler.attributeDecl - attribute declaration: " + eName + " " + aName + " "
691
                + type + " " + valueDefault + " " + value);
692
    }
693

    
694
    /**
695
     * SAX Handler that receives notification of internal entity declarations
696
     */
697
    public void internalEntityDecl(String name, String value)
698
            throws org.xml.sax.SAXException
699
    {
700
        //System.out.println("INTERNENTITYDECL: " + name + " " + value);
701
        logMetacat.debug("DBSaxHandler.internalEntityDecl - internal entity declaration: " + name + " " + value);
702
    }
703

    
704
    /**
705
     * SAX Handler that receives notification of external entity declarations
706
     */
707
    public void externalEntityDecl(String name, String publicId, String systemId)
708
            throws org.xml.sax.SAXException
709
    {
710
        //System.out.println("EXTERNENTITYDECL: " + name + " " + publicId
711
        //                              + " " + systemId);
712
        logMetacat.debug("DBSaxHandler.externalEntityDecl - external entity declaration: " + name + " " + publicId
713
                + " " + systemId);
714
        // it processes other external entity, not the DTD;
715
        // it doesn't signal for the DTD here
716
        processingDTD = false;
717
    }
718

    
719
    //
720
    // the next section implements the ErrorHandler interface
721
    //
722

    
723
    /**
724
     * SAX Handler that receives notification of fatal parsing errors
725
     */
726
    public void fatalError(SAXParseException exception) throws SAXException
727
    {
728
        logMetacat.fatal("DBSaxHandler.fatalError - " + exception.getMessage());
729
        throw (new SAXException("Fatal processing error.", exception));
730
    }
731

    
732
    /**
733
     * SAX Handler that receives notification of recoverable parsing errors
734
     */
735
    public void error(SAXParseException exception) throws SAXException
736
    {
737
        logMetacat.error("DBSaxHandler.error - " + exception.getMessage());
738
        throw (new SAXException(exception.getMessage(), exception));
739
    }
740

    
741
    /**
742
     * SAX Handler that receives notification of warnings
743
     */
744
    public void warning(SAXParseException exception) throws SAXException
745
    {
746
        logMetacat.warn("DBSaxHandler.warning - " + exception.getMessage());
747
        throw (new SAXException(exception.getMessage(), exception));
748
    }
749

    
750
    //
751
    // Helper, getter and setter methods
752
    //
753

    
754
    /**
755
     * get the document name
756
     */
757
    public String getDocname()
758
    {
759
        return docname;
760
    }
761

    
762
    /**
763
     * get the document processing state
764
     */
765
    public boolean processingDTD()
766
    {
767
        return processingDTD;
768
    }
769
    
770
    
771
    /**
772
     * get the the is revision doc
773
     * @return
774
     */
775
    public boolean getIsRevisionDoc()
776
    {
777
        return isRevisionDoc;
778
    }
779
    
780
    /**
781
     * Set the the handler is for revisionDoc
782
     * @param isRevisionDoc
783
     */
784
    public void setIsRevisionDoc(boolean isRevisionDoc)
785
    {
786
       this.isRevisionDoc = isRevisionDoc;   
787
    }
788

    
789
    public String getEncoding() {
790
		return encoding;
791
	}
792

    
793
	public void setEncoding(String encoding) {
794
		this.encoding = encoding;
795
	}
796

    
797
	/* Method to write a text buffer for DBSAXNode */
798
    protected long writeTextForDBSAXNode(long previousEndNodeId,
799
            StringBuffer strBuffer, DBSAXNode node) throws SAXException
800
    {
801
        long nodeId = previousEndNodeId;
802
        // Check parameter
803
        if (strBuffer == null || node == null) { return nodeId; }
804
        boolean moredata = true;
805

    
806
        String normalizedData = strBuffer.toString();
807
        logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - Before normalize in write process: " + normalizedData);
808
        String afterNormalize = MetacatUtil.normalize(normalizedData);
809
        logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - After normalize in write process: " + afterNormalize);
810
        strBuffer = new StringBuffer(afterNormalize);;
811

    
812
        int bufferSize = strBuffer.length();
813
        int start = 0;
814

    
815
        // if there are some cotent in buffer, write it
816
        if (bufferSize > 0) {
817
            logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - Write text into DB");
818

    
819
                // Write the content of the node to the database
820
                nodeId = node.writeChildNodeToDB("TEXT", null, new String(strBuffer), docid);
821
        }//if
822
        return nodeId;
823
    }
824
    
825
    public long getRootNodeId()
826
    {
827
        return rootNode.getNodeID();
828
    }
829
    
830
    public String getDocumentType()
831
    {
832
        return doctype;
833
    }
834
    
835
    public String getDocumentName()
836
    {
837
        return docname;
838
    }
839
    
840
    public String getCatalogId()
841
    {
842
        return catalogid;
843
    }
844
}
(18-18/64)