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: 2012-10-16 13:50:03 -0700 (Tue, 16 Oct 2012) $'
11
 * '$Revision: 7403 $'
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.utilities.triple.Triple;
46
import edu.ucsb.nceas.utilities.triple.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
	protected boolean writeAccessRules = true;   
146
	
147
	protected boolean ignoreDenyFirst = true;
148

    
149
    public static final String ECOGRID = "ecogrid://";
150

    
151
    private Logger logMetacat = Logger.getLogger(DBSAXHandler.class);
152

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

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

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

    
232
    /** SAX Handler that receives notification of beginning of the document */
233
    public void startDocument() throws SAXException
234
    {
235
        logMetacat.debug("DBSaxHandler.startDocument - starting document");
236

    
237
        // Create the document node representation as root
238
        rootNode = new DBSAXNode(connection, this.docid);
239
        // Add the node to the stack, so that any text data can be
240
        // added as it is encountered
241
        nodeStack.push(rootNode);
242
    }
243

    
244
    /** SAX Handler that receives notification of end of the document */
245
	public void endDocument() throws SAXException {
246
		logMetacat.debug("DBSaxHandler.endDocument - ending document");
247
		// Starting new thread for writing XML Index.
248
		// It calls the run method of the thread.
249

    
250
		try {
251
			// if it is data package insert triple into relation table;
252
			if (doctype != null
253
					&& MetacatUtil.getOptionList(
254
							PropertyService.getProperty("xml.packagedoctype")).contains(
255
							doctype) && hasTriple && !isRevisionDoc) {
256

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

    
282
    /** SAX Handler that is called at the start of Namespace */
283
    public void startPrefixMapping(String prefix, String uri)
284
            throws SAXException
285
    {
286
        logMetacat.debug("DBSaxHandler.startPrefixMapping - Starting namespace");
287

    
288
        namespaces.put(prefix, uri);
289
    }
290

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

    
302
        DBSAXNode parentNode = null;
303
        DBSAXNode currentNode = null;
304

    
305
        // Get a reference to the parent node for the id
306
        try {
307
            
308
            parentNode = (DBSAXNode) nodeStack.peek();
309
        } catch (EmptyStackException e) {
310
            parentNode = null;
311
        }
312

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

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

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

    
408
        // Create the current node representation
409
        currentNode = new DBSAXNode(connection, qName, localName,
410
                parentNode, rootNode.getNodeID(), docid, doctype);
411

    
412
        // Add all of the namespaces
413
        String prefix;
414
        String nsuri;
415
        Enumeration<String> prefixes = namespaces.keys();
416
        while (prefixes.hasMoreElements()) {
417
            prefix = (String) prefixes.nextElement();
418
            nsuri = (String) namespaces.get(prefix);
419
            currentNode.setNamespace(prefix, nsuri, docid);
420
        }
421
        namespaces = null;
422
        namespaces = new Hashtable<String,String>();
423

    
424
        // Add all of the attributes
425
        for (int i = 0; i < atts.getLength(); i++) {
426
            String attributeName = atts.getQName(i);
427
            String attributeValue = atts.getValue(i);
428
            endNodeId = currentNode.setAttribute(attributeName, attributeValue,
429
                    docid);
430

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

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

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

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

    
514
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
515

    
516
            // Write the content of the node to the database
517
            endNodeId = currentNode.writeChildNodeToDB("TEXT", null, new String(cbuf, start, len),
518
                    docid);
519
    }
520

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

    
533
    /** SAX Handler that is called at the end of each XML element */
534
    public void endElement(String uri, String localName, String qName)
535
            throws SAXException
536
    {
537
        logMetacat.debug("DBSaxHandler.endElement - End element " + qName);
538

    
539
        // write buffered text nodes into db (so no splited)
540
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
541

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

    
550
            //if it is triple parsing process
551
            if (startParseTriple) {
552

    
553
                String content = textBuffer.toString().trim();
554
                if (localName.equals("subject")) { //get the subject content
555
                    currentTriple.setSubject(content);
556
                } else if (localName.equals("relationship")) { //get the
557
                                                               // relationship
558
                                                               // content
559
                    currentTriple.setRelationship(content);
560
                } else if (localName.equals("object")) { //get the object
561
                                                         // content
562
                    currentTriple.setObject(content);
563
                }
564
            }
565

    
566
        }//if
567

    
568
        //set hitText false
569
        hitTextNode = false;
570
        // reset textbuff
571
        textBuffer = null;
572
        textBuffer = new StringBuffer();
573

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

    
586
    //
587
    // the next section implements the LexicalHandler interface
588
    //
589

    
590
    /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
591
    public void startDTD(String name, String publicId, String systemId)
592
            throws SAXException
593
    {
594
        docname = name;
595
        doctype = publicId;
596
        systemid = systemId;
597

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

    
611
    /**
612
     * SAX Handler that receives notification of end of DTD
613
     */
614
    public void endDTD() throws SAXException
615
    {
616

    
617
        processingDTD = false;
618
        logMetacat.debug("DBSaxHandler.endDTD - Setting processingDTD to false");
619
        logMetacat.debug("DBSaxHandler.endDTD - end DTD");
620
    }
621

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

    
635
    /**
636
     * SAX Handler that receives notification of the start of CDATA sections
637
     */
638
    public void startCDATA() throws SAXException
639
    {
640
        logMetacat.debug("DBSaxHandler.startCDATA - starting CDATA");
641
    }
642

    
643
    /**
644
     * SAX Handler that receives notification of the end of CDATA sections
645
     */
646
    public void endCDATA() throws SAXException
647
    {
648
        logMetacat.debug("DBSaxHandler.endCDATA - end CDATA");
649
    }
650

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

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

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

    
685
    /**
686
     * SAX Handler that receives notification of attribute declarations
687
     */
688
    public void attributeDecl(String eName, String aName, String type,
689
            String valueDefault, String value) throws org.xml.sax.SAXException
690
    {
691

    
692
        //System.out.println("ATTRIBUTEDECL: " + eName + " "
693
        //                        + aName + " " + type + " " + valueDefault + " "
694
        //                        + value);
695
        logMetacat.debug("DBSaxHandler.attributeDecl - attribute declaration: " + eName + " " + aName + " "
696
                + type + " " + valueDefault + " " + value);
697
    }
698

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

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

    
724
    //
725
    // the next section implements the ErrorHandler interface
726
    //
727

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

    
737
    /**
738
     * SAX Handler that receives notification of recoverable parsing errors
739
     */
740
    public void error(SAXParseException exception) throws SAXException
741
    {
742
        logMetacat.error("DBSaxHandler.error - " + exception.getMessage());
743
        throw (new SAXException(exception.getMessage(), exception));
744
    }
745

    
746
    /**
747
     * SAX Handler that receives notification of warnings
748
     */
749
    public void warning(SAXParseException exception) throws SAXException
750
    {
751
        logMetacat.warn("DBSaxHandler.warning - " + exception.getMessage());
752
        throw (new SAXException(exception.getMessage(), exception));
753
    }
754

    
755
    //
756
    // Helper, getter and setter methods
757
    //
758

    
759
    /**
760
     * get the document name
761
     */
762
    public String getDocname()
763
    {
764
        return docname;
765
    }
766

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

    
794
    public String getEncoding() {
795
		return encoding;
796
	}
797

    
798
	public void setEncoding(String encoding) {
799
		this.encoding = encoding;
800
	}
801

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

    
811
        String normalizedData = strBuffer.toString();
812
        logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - Before normalize in write process: " + normalizedData);
813
        String afterNormalize = MetacatUtil.normalize(normalizedData);
814
        logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - After normalize in write process: " + afterNormalize);
815
        strBuffer = new StringBuffer(afterNormalize);;
816

    
817
        int bufferSize = strBuffer.length();
818
        int start = 0;
819

    
820
        // if there are some cotent in buffer, write it
821
        if (bufferSize > 0) {
822
            logMetacat.debug("DBSAXHandler.writeTextForDBSAXNode - Write text into DB");
823

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