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: tao $'
10
 *     '$Date: 2016-09-09 21:58:05 -0700 (Fri, 09 Sep 2016) $'
11
 * '$Revision: 9960 $'
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.trace("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.trace("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.trace("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.trace("DBSaxHandler.startElement - Start ELEMENT(qName) " + qName);
299
        logMetacat.trace("DBSaxHandler.startElement - Start ELEMENT(localName) " + localName);
300
        logMetacat.trace("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
        			//since we don't have format id information here, we set it null
450
        			String formatId = null;
451
        			XMLSchema xmlSchema = 
452
        				new XMLSchema(parsedUri.get(j), parsedUri.get(j + 1), formatId);
453
        			schemaList.add(xmlSchema);
454
        		}
455
            }
456
        }
457

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

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

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

    
516
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
517

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

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

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

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

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

    
552
            //if it is triple parsing process
553
            if (startParseTriple) {
554

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

    
568
        }//if
569

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

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

    
588
    //
589
    // the next section implements the LexicalHandler interface
590
    //
591

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

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

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

    
619
        processingDTD = false;
620
        logMetacat.trace("DBSaxHandler.endDTD - Setting processingDTD to false");
621
        logMetacat.trace("DBSaxHandler.endDTD - end DTD");
622
    }
623

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

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

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

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

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

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

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

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

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

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

    
726
    //
727
    // the next section implements the ErrorHandler interface
728
    //
729

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

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

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

    
757
    //
758
    // Helper, getter and setter methods
759
    //
760

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

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

    
796
    public String getEncoding() {
797
		return encoding;
798
	}
799

    
800
	public void setEncoding(String encoding) {
801
		this.encoding = encoding;
802
	}
803

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

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

    
819
        int bufferSize = strBuffer.length();
820
        int start = 0;
821

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

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