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: berkley $'
10
 *     '$Date: 2007-04-03 13:10:52 -0700 (Tue, 03 Apr 2007) $'
11
 * '$Revision: 3221 $'
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.SQLException;
33
import java.sql.Statement;
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.morpho.datapackage.Triple;
41
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
42

    
43
import org.apache.log4j.Logger;
44
import org.xml.sax.Attributes;
45
import org.xml.sax.SAXException;
46
import org.xml.sax.SAXParseException;
47
import org.xml.sax.ext.DeclHandler;
48
import org.xml.sax.ext.LexicalHandler;
49
import org.xml.sax.helpers.DefaultHandler;
50

    
51
/**
52
 * A database aware Class implementing callback bethods for the SAX parser to
53
 * call when processing the XML stream and generating events.
54
 */
55
public class DBSAXHandler extends DefaultHandler implements LexicalHandler,
56
        DeclHandler
57
{
58

    
59
    protected boolean atFirstElement;
60

    
61
    protected boolean processingDTD;
62

    
63
    protected String docname = null;
64

    
65
    protected String doctype;
66
    
67
    protected String catalogid = null;
68

    
69
    protected String systemid;
70

    
71
    private boolean stackCreated = false;
72

    
73
    protected Stack nodeStack;
74

    
75
    protected Vector nodeIndex;
76

    
77
    protected DBConnection connection = null;
78

    
79
    protected DocumentImpl currentDocument;
80
    
81
    protected String createDate = null;
82
    
83
    protected String updateDate = null;
84

    
85
    protected DBSAXNode rootNode;
86

    
87
    protected String action = null;
88

    
89
    protected String docid = null;
90

    
91
    protected String revision = null;
92

    
93
    protected String user = null;
94

    
95
    protected String[] groups = null;
96

    
97
    protected String pub = null;
98

    
99
    private boolean endDocument = false;
100

    
101
    protected int serverCode = 1;
102

    
103
    protected Hashtable namespaces = new Hashtable();
104

    
105
    protected boolean hitTextNode = false; // a flag to hit text node
106

    
107
    // a buffer to keep all text nodes for same element
108
    // it is for element was splited
109
    protected StringBuffer textBuffer = new StringBuffer();
110

    
111
    protected Stack textBufferStack = new Stack();
112

    
113
    protected static final int MAXDATACHARS = 4000;
114

    
115
    //protected static final int MAXDATACHARS = 50;
116

    
117
    // methods writeChildNodeToDB, setAttribute, setNamespace,
118
    // writeTextForDBSAXNode will increase endNodeId.
119
    protected long endNodeId = -1; // The end node id for a substree
120
    // DOCTITLE attr cleared from the db
121
    //   private static final int MAXTITLELEN = 1000;
122
    
123
    private boolean isRevisionDoc  = false;
124

    
125
    //HandlerTriple stuff
126
    TripleCollection tripleList = new TripleCollection();
127

    
128
    Triple currentTriple = new Triple();
129

    
130
    boolean startParseTriple = false;
131

    
132
    boolean hasTriple = false;
133

    
134
    public static final String ECOGRID = "ecogrid://";
135

    
136
    private Logger logMetacat = Logger.getLogger(DBSAXHandler.class);
137

    
138
    /**
139
     * Construct an instance of the handler class
140
     *
141
     * @param conn the JDBC connection to which information is written
142
     */
143
    private DBSAXHandler(DBConnection conn, String createDate, String updateDate)
144
    {
145
        this.connection = conn;
146
        this.atFirstElement = true;
147
        this.processingDTD = false;
148
        this.createDate = createDate;
149
        this.updateDate = updateDate;
150

    
151
        // Create the stack for keeping track of node context
152
        // if it doesn't already exist
153
        if (!stackCreated) {
154
            nodeStack = new Stack();
155
            nodeIndex = new Vector();
156
            stackCreated = true;
157
        }
158
    }
159

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

    
216
    /** SAX Handler that receives notification of beginning of the document */
217
    public void startDocument() throws SAXException
218
    {
219
        logMetacat.info("start Document");
220

    
221
        // Create the document node representation as root
222
        rootNode = new DBSAXNode(connection, this.docid);
223
        // Add the node to the stack, so that any text data can be
224
        // added as it is encountered
225
        nodeStack.push(rootNode);
226
    }
227

    
228
    /** SAX Handler that receives notification of end of the document */
229
    public void endDocument() throws SAXException
230
    {
231
        logMetacat.info("end Document");
232
        // Starting new thread for writing XML Index.
233
        // It calls the run method of the thread.
234

    
235
        //if it is data package insert triple into relationtion table;
236
        if (doctype != null
237
                && MetaCatUtil.getOptionList(
238
                        MetaCatUtil.getOption("packagedoctype")).contains(
239
                        doctype) && hasTriple && !isRevisionDoc) {
240
            try {
241
                //initial handler and write into relationdb only for xml-documents
242
                if (!isRevisionDoc)
243
                {
244
                  RelationHandler handler = new RelationHandler(docid, doctype,
245
                        connection, tripleList);
246
                }
247
            } catch (Exception e) {
248
                logMetacat.error(
249
                        "Failed to write triples into relation table"
250
                                + e.getMessage());
251
                throw new SAXException(
252
                        "Failed to write triples into relation table "
253
                                + e.getMessage());
254
            }
255
        }
256
    }
257

    
258
    /** SAX Handler that is called at the start of Namespace */
259
    public void startPrefixMapping(String prefix, String uri)
260
            throws SAXException
261
    {
262
        logMetacat.info("NAMESPACE");
263

    
264
        namespaces.put(prefix, uri);
265
    }
266

    
267
    /** SAX Handler that is called at the start of each XML element */
268
    public void startElement(String uri, String localName, String qName,
269
            Attributes atts) throws SAXException
270
    {
271
        // for element <eml:eml...> qname is "eml:eml", local name is "eml"
272
        // for element <acl....> both qname and local name is "eml"
273
        // uri is namesapce
274
        logMetacat.info("Start ELEMENT(qName) " + qName);
275
        logMetacat.info("Start ELEMENT(localName) " + localName);
276
        logMetacat.info("Start ELEMENT(uri) " + uri);
277

    
278
        DBSAXNode parentNode = null;
279
        DBSAXNode currentNode = null;
280

    
281
        // Get a reference to the parent node for the id
282
        try {
283
            
284
            parentNode = (DBSAXNode) nodeStack.peek();
285
        } catch (EmptyStackException e) {
286
            parentNode = null;
287
        }
288

    
289
        // If hit a text node, we need write this text for current's parent
290
        // node
291
        // This will happend if the element is mixted
292
        if (hitTextNode && parentNode != null) {
293
            // write the textbuffer into db for parent node.
294
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, parentNode);
295
            // rest hitTextNode
296
            hitTextNode = false;
297
            // reset textbuffer
298
            textBuffer = null;
299
            textBuffer = new StringBuffer();
300
           
301
        }
302
        
303
        // Document representation that points to the root document node
304
        if (atFirstElement) {
305
            atFirstElement = false;
306
            // If no DOCTYPE declaration: docname = root element
307
            // doctype = root element name or name space
308
            if (docname == null) {
309
                docname = localName;
310
                // if uri isn't null doctype = uri(namespace)
311
                // othewise root element
312
                if (uri != null && !(uri.trim()).equals("")) {
313
                    doctype = uri;
314
                } else {
315
                    doctype = docname;
316
                }
317
                logMetacat.info("DOCNAME-a: " + docname);
318
                logMetacat.info("DOCTYPE-a: " + doctype);
319
            } else if (doctype == null) {
320
                // because docname is not null and it is declared in dtd
321
                // so could not be in schema, no namespace
322
                doctype = docname;
323
                logMetacat.info("DOCTYPE-b: " + doctype);
324
            }
325
           
326
            rootNode.writeNodename(docname);
327
          
328
            try {
329
                // for validated XML Documents store a reference to XML DB
330
                // Catalog
331
                // Because this is select statement and it needn't to roll back
332
                // if
333
                // insert document action fialed.
334
                // In order to decrease DBConnection usage count, we get a new
335
                // dbconnection from pool
336
               
337
                DBConnection dbConn = null;
338
                int serialNumber = -1;
339
               
340
                if (systemid != null) {
341
                    try {
342
                        // Get dbconnection
343
                        dbConn = DBConnectionPool
344
                                .getDBConnection("DBSAXHandler.startElement");
345
                        serialNumber = dbConn.getCheckOutSerialNumber();
346

    
347
                        Statement stmt = dbConn.createStatement();
348
                        ResultSet rs = stmt
349
                                .executeQuery("SELECT catalog_id FROM xml_catalog "
350
                                        + "WHERE entry_type = 'DTD' "
351
                                        + "AND public_id = '" + doctype + "'");
352
                        boolean hasRow = rs.next();
353
                        if (hasRow) {
354
                            catalogid = rs.getString(1);
355
                        }
356
                        stmt.close();
357
                    }//try
358
                    finally {
359
                        // Return dbconnection
360
                        DBConnectionPool.returnDBConnection(dbConn,
361
                                serialNumber);
362
                    }//finally
363
                }
364

    
365
                //create documentImpl object by the constructor which can
366
                // specify
367
                //the revision
368
              
369
                if (!isRevisionDoc)
370
                {
371
                  currentDocument = new DocumentImpl(connection, rootNode
372
                        .getNodeID(), docname, doctype, docid, revision,
373
                        action, user, this.pub, catalogid, this.serverCode, 
374
                        createDate, updateDate);
375
                }               
376
            } catch (Exception ane) {
377
                ane.printStackTrace();
378
                throw (new SAXException("Error in DBSaxHandler.startElement "
379
                        + action, ane));
380
            }
381
        }
382

    
383
        // Create the current node representation
384
        currentNode = new DBSAXNode(connection, qName, localName,
385
                parentNode, rootNode.getNodeID(), docid, doctype);
386

    
387
        // Add all of the namespaces
388
        String prefix;
389
        String nsuri;
390
        Enumeration prefixes = namespaces.keys();
391
        while (prefixes.hasMoreElements()) {
392
            prefix = (String) prefixes.nextElement();
393
            nsuri = (String) namespaces.get(prefix);
394
            currentNode.setNamespace(prefix, nsuri, docid);
395
        }
396
        namespaces = null;
397
        namespaces = new Hashtable();
398

    
399
        // Add all of the attributes
400
        for (int i = 0; i < atts.getLength(); i++) {
401
            String attributeName = atts.getQName(i);
402
            String attributeValue = atts.getValue(i);
403
            endNodeId = currentNode.setAttribute(attributeName, attributeValue,
404
                    docid);
405

    
406
            // To handle name space and schema location if the attribute name
407
            // is
408
            // xsi:schemaLocation. If the name space is in not in catalog table
409
            // it will be regeistered.
410
            if (attributeName != null
411
                    && attributeName
412
                            .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
413
                SchemaLocationResolver resolver = new SchemaLocationResolver(
414
                        attributeValue);
415
                resolver.resolveNameSpace();
416

    
417
            }
418
        }
419

    
420
        // Add the node to the stack, so that any text data can be
421
        // added as it is encountered
422
        nodeStack.push(currentNode);
423
        // Add the node to the vector used by thread for writing XML Index
424
        nodeIndex.addElement(currentNode);
425
        // start parsing triple
426
        if (doctype != null
427
                && MetaCatUtil.getOptionList(
428
                        MetaCatUtil.getOption("packagedoctype")).contains(
429
                        doctype) && localName.equals("triple")) {
430
            startParseTriple = true;
431
            hasTriple = true;
432
            currentTriple = new Triple();
433
        }
434
    }    
435

    
436
    /** SAX Handler that is called for each XML text node */
437
    public void characters(char[] cbuf, int start, int len) throws SAXException
438
    {
439
        logMetacat.info("CHARACTERS");
440
        // buffer all text nodes for same element. This is for text was splited
441
        // into different nodes
442
        textBuffer.append(new String(cbuf, start, len));
443
        // set hittextnode true
444
        hitTextNode = true;
445
        // if text buffer .size is greater than max, write it to db.
446
        // so we can save memory
447
        if (textBuffer.length() > MAXDATACHARS) {
448
            logMetacat.info("Write text into DB in charaters"
449
                    + " when text buffer size is greater than maxmum number");
450
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
451
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
452
                    currentNode);
453
            textBuffer = null;
454
            textBuffer = new StringBuffer();
455
        }
456
    }
457

    
458
    /**
459
     * SAX Handler that is called for each XML text node that is Ignorable
460
     * white space
461
     */
462
    public void ignorableWhitespace(char[] cbuf, int start, int len)
463
            throws SAXException
464
    {
465
        // When validation is turned "on", white spaces are reported here
466
        // When validation is turned "off" white spaces are not reported here,
467
        // but through characters() callback
468
        logMetacat.info("IGNORABLEWHITESPACE");
469

    
470
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
471
        String data = null;
472
        int leftover = len;
473
        int offset = start;
474
        boolean moredata = true;
475

    
476
        // This loop deals with the case where there are more characters
477
        // than can fit in a single database text field (limit is
478
        // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
479
        // write a series of nodes that are MAXDATACHARS long, and then the
480
        // final node contains the remainder
481
        while (moredata) {
482
            if (leftover > MAXDATACHARS) {
483
                data = new String(cbuf, offset, MAXDATACHARS);
484
                leftover -= MAXDATACHARS;
485
                offset += MAXDATACHARS;
486
            } else {
487
                data = new String(cbuf, offset, leftover);
488
                moredata = false;
489
            }
490

    
491
            // Write the content of the node to the database
492
            endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
493
                    docid);
494
        }
495
    }
496

    
497
    /**
498
     * SAX Handler called once for each processing instruction found: node that
499
     * PI may occur before or after the root element.
500
     */
501
    public void processingInstruction(String target, String data)
502
            throws SAXException
503
    {
504
        logMetacat.info("PI");
505
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
506
        endNodeId = currentNode.writeChildNodeToDB("PI", target, data, docid);
507
    }
508

    
509
    /** SAX Handler that is called at the end of each XML element */
510
    public void endElement(String uri, String localName, String qName)
511
            throws SAXException
512
    {
513
        logMetacat.info("End ELEMENT " + qName);
514

    
515
        // write buffered text nodes into db (so no splited)
516
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
517

    
518
        // If before the end element, the parser hit text nodes and store them
519
        // into the buffer, write the buffer to data base. The reason we put
520
        // write database here is for xerces some time split text node
521
        if (hitTextNode) {
522
            logMetacat.info("Write text into DB in End Element");
523
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
524
                    currentNode);
525

    
526
            //if it is triple parsing process
527
            if (startParseTriple) {
528

    
529
                String content = textBuffer.toString().trim();
530
                if (localName.equals("subject")) { //get the subject content
531
                    currentTriple.setSubject(content);
532
                } else if (localName.equals("relationship")) { //get the
533
                                                               // relationship
534
                                                               // content
535
                    currentTriple.setRelationship(content);
536
                } else if (localName.equals("object")) { //get the object
537
                                                         // content
538
                    currentTriple.setObject(content);
539
                }
540
            }
541

    
542
        }//if
543

    
544
        //set hitText false
545
        hitTextNode = false;
546
        // reset textbuff
547
        textBuffer = null;
548
        textBuffer = new StringBuffer();
549

    
550
        // Get the node from the stack
551
        currentNode = (DBSAXNode) nodeStack.pop();
552
        //finishing parsing single triple
553
        if (startParseTriple && localName.equals("triple")) {
554
            // add trip to triple collection
555
            tripleList.addTriple(currentTriple);
556
            //rest variable
557
            currentTriple = null;
558
            startParseTriple = false;
559
        }
560
    }
561

    
562
    //
563
    // the next section implements the LexicalHandler interface
564
    //
565

    
566
    /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
567
    public void startDTD(String name, String publicId, String systemId)
568
            throws SAXException
569
    {
570
        docname = name;
571
        doctype = publicId;
572
        systemid = systemId;
573

    
574
        processingDTD = true;
575
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
576
        //create a DTD node and write docname,publicid and system id into db
577
        // we don't put the dtd node into node stack
578
        DBSAXNode dtdNode = new DBSAXNode(connection, name, publicId, systemId,
579
                currentNode, currentNode.getRootNodeID(), docid);
580
        logMetacat.info("Start DTD");
581
        logMetacat.info("Setting processingDTD to true");
582
        logMetacat.info("DOCNAME: " + docname);
583
        logMetacat.info("DOCTYPE: " + doctype);
584
        logMetacat.info("  SYSID: " + systemid);
585
    }
586

    
587
    /**
588
     * SAX Handler that receives notification of end of DTD
589
     */
590
    public void endDTD() throws SAXException
591
    {
592

    
593
        processingDTD = false;
594
        logMetacat.info("Setting processingDTD to false");
595
        logMetacat.info("end DTD");
596
    }
597

    
598
    /**
599
     * SAX Handler that receives notification of comments in the DTD
600
     */
601
    public void comment(char[] ch, int start, int length) throws SAXException
602
    {
603
        logMetacat.info("COMMENT");
604
        if (!processingDTD) {
605
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
606
            endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
607
                    new String(ch, start, length), docid);
608
        }
609
    }
610

    
611
    /**
612
     * SAX Handler that receives notification of the start of CDATA sections
613
     */
614
    public void startCDATA() throws SAXException
615
    {
616
        logMetacat.info("start CDATA");
617
    }
618

    
619
    /**
620
     * SAX Handler that receives notification of the end of CDATA sections
621
     */
622
    public void endCDATA() throws SAXException
623
    {
624
        logMetacat.info("end CDATA");
625
    }
626

    
627
    /**
628
     * SAX Handler that receives notification of the start of entities
629
     */
630
    public void startEntity(String name) throws SAXException
631
    {
632
        logMetacat.info("start ENTITY: " + name);
633
        //System.out.println("start ENTITY: " + name);
634
        if (name.equals("[dtd]")) {
635
            processingDTD = true;
636
        }
637
    }
638

    
639
    /**
640
     * SAX Handler that receives notification of the end of entities
641
     */
642
    public void endEntity(String name) throws SAXException
643
    {
644
        logMetacat.info("end ENTITY: " + name);
645
        //System.out.println("end ENTITY: " + name);
646
        if (name.equals("[dtd]")) {
647
            processingDTD = false;
648
        }
649
    }
650

    
651
    /**
652
     * SAX Handler that receives notification of element declarations
653
     */
654
    public void elementDecl(String name, String model)
655
            throws org.xml.sax.SAXException
656
    {
657
        //System.out.println("ELEMENTDECL: " + name + " " + model);
658
        logMetacat.info("ELEMENTDECL: " + name + " " + model);
659
    }
660

    
661
    /**
662
     * SAX Handler that receives notification of attribute declarations
663
     */
664
    public void attributeDecl(String eName, String aName, String type,
665
            String valueDefault, String value) throws org.xml.sax.SAXException
666
    {
667

    
668
        //System.out.println("ATTRIBUTEDECL: " + eName + " "
669
        //                        + aName + " " + type + " " + valueDefault + " "
670
        //                        + value);
671
        logMetacat.info("ATTRIBUTEDECL: " + eName + " " + aName + " "
672
                + type + " " + valueDefault + " " + value);
673
    }
674

    
675
    /**
676
     * SAX Handler that receives notification of internal entity declarations
677
     */
678
    public void internalEntityDecl(String name, String value)
679
            throws org.xml.sax.SAXException
680
    {
681
        //System.out.println("INTERNENTITYDECL: " + name + " " + value);
682
        logMetacat.info("INTERNENTITYDECL: " + name + " " + value);
683
    }
684

    
685
    /**
686
     * SAX Handler that receives notification of external entity declarations
687
     */
688
    public void externalEntityDecl(String name, String publicId, String systemId)
689
            throws org.xml.sax.SAXException
690
    {
691
        //System.out.println("EXTERNENTITYDECL: " + name + " " + publicId
692
        //                              + " " + systemId);
693
        logMetacat.info("EXTERNENTITYDECL: " + name + " " + publicId
694
                + " " + systemId);
695
        // it processes other external entity, not the DTD;
696
        // it doesn't signal for the DTD here
697
        processingDTD = false;
698
    }
699

    
700
    //
701
    // the next section implements the ErrorHandler interface
702
    //
703

    
704
    /**
705
     * SAX Handler that receives notification of fatal parsing errors
706
     */
707
    public void fatalError(SAXParseException exception) throws SAXException
708
    {
709
        logMetacat.fatal("FATALERROR: " + exception.getMessage());
710
        throw (new SAXException("Fatal processing error.", exception));
711
    }
712

    
713
    /**
714
     * SAX Handler that receives notification of recoverable parsing errors
715
     */
716
    public void error(SAXParseException exception) throws SAXException
717
    {
718
        logMetacat.error("ERROR: " + exception.getMessage());
719
        throw (new SAXException("Error in processing EML.", exception));
720
    }
721

    
722
    /**
723
     * SAX Handler that receives notification of warnings
724
     */
725
    public void warning(SAXParseException exception) throws SAXException
726
    {
727
        logMetacat.warn("WARNING: " + exception.getMessage());
728
        throw (new SAXException("Warning.", exception));
729
    }
730

    
731
    //
732
    // Helper, getter and setter methods
733
    //
734

    
735
    /**
736
     * get the document name
737
     */
738
    public String getDocname()
739
    {
740
        return docname;
741
    }
742

    
743
    /**
744
     * get the document processing state
745
     */
746
    public boolean processingDTD()
747
    {
748
        return processingDTD;
749
    }
750
    
751
    
752
    /**
753
     * get the the is revision doc
754
     * @return
755
     */
756
    public boolean getIsRevisionDoc()
757
    {
758
        return isRevisionDoc;
759
    }
760
    
761
    /**
762
     * Set the the handler is for revisionDoc
763
     * @param isRevisionDoc
764
     */
765
    public void setIsRevisionDoc(boolean isRevisionDoc)
766
    {
767
       this.isRevisionDoc = isRevisionDoc;   
768
    }
769

    
770
    /* Method to write a text buffer for DBSAXNode */
771
    protected long writeTextForDBSAXNode(long previousEndNodeId,
772
            StringBuffer strBuffer, DBSAXNode node) throws SAXException
773
    {
774
        long nodeId = previousEndNodeId;
775
        // Check parameter
776
        if (strBuffer == null || node == null) { return nodeId; }
777
        boolean moredata = true;
778
        String data = null;
779

    
780
        String normalizedData = strBuffer.toString();
781
        strBuffer = new StringBuffer(MetaCatUtil.normalize(normalizedData));
782

    
783
        int bufferSize = strBuffer.length();
784
        int start = 0;
785

    
786
        // if there are some cotent in buffer, write it
787
        if (bufferSize > 0) {
788
            logMetacat.info("Write text into DB");
789
            // This loop deals with the case where there are more characters
790
            // than can fit in a single database text field (limit is
791
            // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
792
            // write a series of nodes that are MAXDATACHARS long, and then the
793
            // final node contains the remainder
794
            while (moredata) {
795
                bufferSize = strBuffer.length();
796
                if (bufferSize > MAXDATACHARS) {
797
                    data = strBuffer.substring(start, MAXDATACHARS);
798
                    // cut the stringbuffer part that already written into db
799
                    strBuffer = strBuffer.delete(start, MAXDATACHARS);
800
                } else {
801
                    data = strBuffer.substring(start, bufferSize);
802
                    moredata = false;
803
                }
804

    
805
                // Write the content of the node to the database
806
                nodeId = node.writeChildNodeToDB("TEXT", null, data, docid);
807
            }//while
808
        }//if
809
        return nodeId;
810
    }
811
    
812
    public long getRootNodeId()
813
    {
814
        return rootNode.getNodeID();
815
    }
816
    
817
    public String getDocumentType()
818
    {
819
        return doctype;
820
    }
821
    
822
    public String getDocumentName()
823
    {
824
        return docname;
825
    }
826
    
827
    public String getCatalogId()
828
    {
829
        return catalogid;
830
    }
831
}
(22-22/66)