Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that handles the SAX XML events as they
4
 *             are generated from XML documents
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Matt Jones, Jivka Bojilova
8
 *    Release: @release@
9
 *
10
 *   '$Author: tao $'
11
 *     '$Date: 2005-10-02 15:37:25 -0700 (Sun, 02 Oct 2005) $'
12
 * '$Revision: 2627 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

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

    
41
import edu.ucsb.nceas.morpho.datapackage.Triple;
42
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
43

    
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, Runnable
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
    protected Thread xmlIndex;
100

    
101
    private boolean endDocument = false;
102

    
103
    protected int serverCode = 1;
104

    
105
    protected Hashtable namespaces = new Hashtable();
106

    
107
    protected boolean hitTextNode = false; // a flag to hit text node
108

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

    
113
    protected Stack textBufferStack = new Stack();
114

    
115
    protected static final int MAXDATACHARS = 4000;
116

    
117
    //protected static final int MAXDATACHARS = 50;
118
    protected static final long INDEXDELAY = 10000;
119

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

    
128
    //HandlerTriple stuff
129
    TripleCollection tripleList = new TripleCollection();
130

    
131
    Triple currentTriple = new Triple();
132

    
133
    boolean startParseTriple = false;
134

    
135
    boolean hasTriple = false;
136

    
137
    public static final String ECOGRID = "ecogrid://";
138

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

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

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

    
218
    /** SAX Handler that receives notification of beginning of the document */
219
    public void startDocument() throws SAXException
220
    {
221
        MetaCatUtil.debugMessage("start Document", 50);
222

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

    
230
    /** SAX Handler that receives notification of end of the document */
231
    public void endDocument() throws SAXException
232
    {
233
        MetaCatUtil.debugMessage("end Document", 50);
234
        // Starting new thread for writing XML Index.
235
        // It calls the run method of the thread.
236

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

    
260
    /** SAX Handler that is called at the start of Namespace */
261
    public void startPrefixMapping(String prefix, String uri)
262
            throws SAXException
263
    {
264
        MetaCatUtil.debugMessage("NAMESPACE", 50);
265

    
266
        namespaces.put(prefix, uri);
267
    }
268

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

    
280
        DBSAXNode parentNode = null;
281
        DBSAXNode currentNode = null;
282

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

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

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

    
367
                //create documentImpl object by the constructor which can
368
                // specify
369
                //the revision
370
              
371
                if (!isRevisionDoc)
372
                {
373
                  //System.out.println("here!!!!!!!!!!!3");
374
                  currentDocument = new DocumentImpl(connection, rootNode
375
                        .getNodeID(), docname, doctype, docid, revision,
376
                        action, user, this.pub, catalogid, this.serverCode, 
377
                        createDate, updateDate);
378
                  //System.out.println("here!!!!!!!!!!!4");
379
                }
380
               
381

    
382
            } catch (Exception ane) {
383
                ane.printStackTrace();
384
                throw (new SAXException("Error in DBSaxHandler.startElement "
385
                        + action, ane));
386
            }
387
        }
388

    
389
        // Create the current node representation
390
        currentNode = new DBSAXNode(connection, qName, localName,
391
                parentNode, rootNode.getNodeID(), docid, doctype);
392

    
393
        // Add all of the namespaces
394
        String prefix;
395
        String nsuri;
396
        Enumeration prefixes = namespaces.keys();
397
        while (prefixes.hasMoreElements()) {
398
            prefix = (String) prefixes.nextElement();
399
            nsuri = (String) namespaces.get(prefix);
400
            currentNode.setNamespace(prefix, nsuri, docid);
401
        }
402
        namespaces = null;
403
        namespaces = new Hashtable();
404

    
405
        // Add all of the attributes
406
        for (int i = 0; i < atts.getLength(); i++) {
407
            String attributeName = atts.getQName(i);
408
            String attributeValue = atts.getValue(i);
409
            endNodeId = currentNode.setAttribute(attributeName, attributeValue,
410
                    docid);
411

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

    
423
            }
424
        }
425

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

    
442
    public void runIndexingThread(){
443
        boolean useXMLIndex =
444
            (new Boolean(MetaCatUtil.getOption("usexmlindex"))).booleanValue();
445
        if (useXMLIndex && !isRevisionDoc) {
446
            try {
447
                xmlIndex.start();
448
            } catch (NullPointerException e) {
449
                xmlIndex = null;
450
                MetaCatUtil.debugMessage("Error in DBSAXHandler.runIndexingThread() "
451
                        + e.getMessage(), 20);
452
            }
453
        }
454
    }
455
    
456
    /*
457
     * Run a separate thread to build the XML index for this document.  This
458
     * thread is run asynchronously in order to more quickly return control to
459
     * the submitting user.  The run method checks to see if the document has
460
     * been fully inserted before trying to update the xml_index table.
461
     */
462
    public void run()
463
    {
464
        try {
465
            if (!isRevisionDoc)
466
            {
467
             // stop 5 second
468
             Thread.sleep(5000);
469
             //make sure record is done
470
             checkDocumentTable();
471
             // Build the index for this document
472
             currentDocument.buildIndex();
473
            }
474
        } catch (Exception e) {
475
            MetaCatUtil.debugMessage("Error in DBSAXHandler.run "
476
                    + e.getMessage(), 30);
477
        }
478
    }
479

    
480
    /*
481
     * method to make sure insert is finished before create index table If new
482
     * version of record is in xml_documents every thing will be fine
483
     */
484
    private void checkDocumentTable() throws Exception
485
    {
486

    
487
        DBConnection dbConn = null;
488
        int serialNumber = -1;
489

    
490
        try {
491
            // Opening separate db connection for writing XML Index
492
            dbConn = DBConnectionPool
493
                    .getDBConnection("DBSAXHandler.checkDocumentTable");
494
            serialNumber = dbConn.getCheckOutSerialNumber();
495

    
496
            // the following while loop construct checks to make sure that
497
            // the docid of the document that we are trying to index is already
498
            // in the xml_documents table. if this is not the case, the foreign
499
            // key relationship between xml_documents and xml_index is
500
            // temporarily broken causing multiple problems.
501
            boolean inxmldoc = false;
502
            long startTime = System.currentTimeMillis();
503
            while (!inxmldoc) {
504
                String xmlDocumentsCheck = "select distinct docid from xml_documents"
505
                        + " where docid ='"
506
                        + docid
507
                        + "' and "
508
                        + " rev ='"
509
                        + revision + "'";
510

    
511
                PreparedStatement xmlDocCheck = dbConn
512
                        .prepareStatement(xmlDocumentsCheck);
513
                // Increase usage count
514
                dbConn.increaseUsageCount(1);
515
                xmlDocCheck.execute();
516
                ResultSet doccheckRS = xmlDocCheck.getResultSet();
517
                boolean tableHasRows = doccheckRS.next();
518
                if (tableHasRows) {
519
                    MetaCatUtil.debugMessage(
520
                            "=========== found the correct document", 35);
521
                    inxmldoc = true;
522
                }
523
                doccheckRS.close();
524
                xmlDocCheck.close();
525
                // make sure the while loop will be ended in reseaonable time
526
                long stopTime = System.currentTimeMillis();
527
                if ((stopTime - startTime) > INDEXDELAY) { throw new Exception(
528
                        "Couldn't find the docid for index build in "
529
                                + "reseaonable time!"); }
530
            }//while
531
        } catch (Exception e) {
532
            try {
533
                dbConn.rollback();
534
                //dbconn.close();
535
            } catch (SQLException sqle) {
536
            }
537
            MetaCatUtil.debugMessage("Error in DBSAXHandler.checkDocumentTable "
538
                    + e.getMessage(), 30);
539

    
540
        } finally {
541
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
542
        }//finally
543

    
544
    }
545

    
546
    /** SAX Handler that is called for each XML text node */
547
    public void characters(char[] cbuf, int start, int len) throws SAXException
548
    {
549
        MetaCatUtil.debugMessage("CHARACTERS", 50);
550
        // buffer all text nodes for same element. This is for text was splited
551
        // into different nodes
552
        textBuffer.append(new String(cbuf, start, len));
553
        // set hittextnode true
554
        hitTextNode = true;
555
        // if text buffer .size is greater than max, write it to db.
556
        // so we can save memory
557
        if (textBuffer.length() > MAXDATACHARS) {
558
            MetaCatUtil.debugMessage("Write text into DB in charaters"
559
                    + " when text buffer size is greater than maxmum number",
560
                    50);
561
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
562
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
563
                    currentNode);
564
            textBuffer = null;
565
            textBuffer = new StringBuffer();
566
        }
567
    }
568

    
569
    /**
570
     * SAX Handler that is called for each XML text node that is Ignorable
571
     * white space
572
     */
573
    public void ignorableWhitespace(char[] cbuf, int start, int len)
574
            throws SAXException
575
    {
576
        // When validation is turned "on", white spaces are reported here
577
        // When validation is turned "off" white spaces are not reported here,
578
        // but through characters() callback
579
        MetaCatUtil.debugMessage("IGNORABLEWHITESPACE", 50);
580

    
581
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
582
        String data = null;
583
        int leftover = len;
584
        int offset = start;
585
        boolean moredata = true;
586

    
587
        // This loop deals with the case where there are more characters
588
        // than can fit in a single database text field (limit is
589
        // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
590
        // write a series of nodes that are MAXDATACHARS long, and then the
591
        // final node contains the remainder
592
        while (moredata) {
593
            if (leftover > MAXDATACHARS) {
594
                data = new String(cbuf, offset, MAXDATACHARS);
595
                leftover -= MAXDATACHARS;
596
                offset += MAXDATACHARS;
597
            } else {
598
                data = new String(cbuf, offset, leftover);
599
                moredata = false;
600
            }
601

    
602
            // Write the content of the node to the database
603
            endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
604
                    docid);
605
        }
606
    }
607

    
608
    /**
609
     * SAX Handler called once for each processing instruction found: node that
610
     * PI may occur before or after the root element.
611
     */
612
    public void processingInstruction(String target, String data)
613
            throws SAXException
614
    {
615
        MetaCatUtil.debugMessage("PI", 50);
616
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
617
        endNodeId = currentNode.writeChildNodeToDB("PI", target, data, docid);
618
    }
619

    
620
    /** SAX Handler that is called at the end of each XML element */
621
    public void endElement(String uri, String localName, String qName)
622
            throws SAXException
623
    {
624
        MetaCatUtil.debugMessage("End ELEMENT " + qName, 50);
625

    
626
        // write buffered text nodes into db (so no splited)
627
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
628

    
629
        // If before the end element, the parser hit text nodes and store them
630
        // into the buffer, write the buffer to data base. The reason we put
631
        // write database here is for xerces some time split text node
632
        if (hitTextNode) {
633
            MetaCatUtil.debugMessage("Write text into DB in End Element", 50);
634
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
635
                    currentNode);
636

    
637
            //if it is triple parsing process
638
            if (startParseTriple) {
639

    
640
                String content = textBuffer.toString().trim();
641
                if (localName.equals("subject")) { //get the subject content
642
                    currentTriple.setSubject(content);
643
                } else if (localName.equals("relationship")) { //get the
644
                                                               // relationship
645
                                                               // content
646
                    currentTriple.setRelationship(content);
647
                } else if (localName.equals("object")) { //get the object
648
                                                         // content
649
                    currentTriple.setObject(content);
650
                }
651
            }
652

    
653
        }//if
654

    
655
        //set hitText false
656
        hitTextNode = false;
657
        // reset textbuff
658
        textBuffer = null;
659
        textBuffer = new StringBuffer();
660

    
661
        // Get the node from the stack
662
        currentNode = (DBSAXNode) nodeStack.pop();
663
        //finishing parsing single triple
664
        if (startParseTriple && localName.equals("triple")) {
665
            // add trip to triple collection
666
            tripleList.addTriple(currentTriple);
667
            //rest variable
668
            currentTriple = null;
669
            startParseTriple = false;
670
        }
671
    }
672

    
673
    //
674
    // the next section implements the LexicalHandler interface
675
    //
676

    
677
    /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
678
    public void startDTD(String name, String publicId, String systemId)
679
            throws SAXException
680
    {
681
        docname = name;
682
        doctype = publicId;
683
        systemid = systemId;
684

    
685
        processingDTD = true;
686
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
687
        //create a DTD node and write docname,publicid and system id into db
688
        // we don't put the dtd node into node stack
689
        DBSAXNode dtdNode = new DBSAXNode(connection, name, publicId, systemId,
690
                currentNode, currentNode.getRootNodeID(), docid);
691
        MetaCatUtil.debugMessage("Start DTD", 50);
692
        MetaCatUtil.debugMessage("Setting processingDTD to true", 50);
693
        MetaCatUtil.debugMessage("DOCNAME: " + docname, 50);
694
        MetaCatUtil.debugMessage("DOCTYPE: " + doctype, 50);
695
        MetaCatUtil.debugMessage("  SYSID: " + systemid, 50);
696
    }
697

    
698
    /**
699
     * SAX Handler that receives notification of end of DTD
700
     */
701
    public void endDTD() throws SAXException
702
    {
703

    
704
        processingDTD = false;
705
        MetaCatUtil.debugMessage("Setting processingDTD to false", 50);
706
        MetaCatUtil.debugMessage("end DTD", 50);
707
    }
708

    
709
    /**
710
     * SAX Handler that receives notification of comments in the DTD
711
     */
712
    public void comment(char[] ch, int start, int length) throws SAXException
713
    {
714
        MetaCatUtil.debugMessage("COMMENT", 50);
715
        if (!processingDTD) {
716
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
717
            endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
718
                    new String(ch, start, length), docid);
719
        }
720
    }
721

    
722
    /**
723
     * SAX Handler that receives notification of the start of CDATA sections
724
     */
725
    public void startCDATA() throws SAXException
726
    {
727
        MetaCatUtil.debugMessage("start CDATA", 50);
728
    }
729

    
730
    /**
731
     * SAX Handler that receives notification of the end of CDATA sections
732
     */
733
    public void endCDATA() throws SAXException
734
    {
735
        MetaCatUtil.debugMessage("end CDATA", 50);
736
    }
737

    
738
    /**
739
     * SAX Handler that receives notification of the start of entities
740
     */
741
    public void startEntity(String name) throws SAXException
742
    {
743
        MetaCatUtil.debugMessage("start ENTITY: " + name, 50);
744
        //System.out.println("start ENTITY: " + name);
745
        if (name.equals("[dtd]")) {
746
            processingDTD = true;
747
        }
748
    }
749

    
750
    /**
751
     * SAX Handler that receives notification of the end of entities
752
     */
753
    public void endEntity(String name) throws SAXException
754
    {
755
        MetaCatUtil.debugMessage("end ENTITY: " + name, 50);
756
        //System.out.println("end ENTITY: " + name);
757
        if (name.equals("[dtd]")) {
758
            processingDTD = false;
759
        }
760
    }
761

    
762
    /**
763
     * SAX Handler that receives notification of element declarations
764
     */
765
    public void elementDecl(String name, String model)
766
            throws org.xml.sax.SAXException
767
    {
768
        //System.out.println("ELEMENTDECL: " + name + " " + model);
769
        MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model, 50);
770
    }
771

    
772
    /**
773
     * SAX Handler that receives notification of attribute declarations
774
     */
775
    public void attributeDecl(String eName, String aName, String type,
776
            String valueDefault, String value) throws org.xml.sax.SAXException
777
    {
778

    
779
        //System.out.println("ATTRIBUTEDECL: " + eName + " "
780
        //                        + aName + " " + type + " " + valueDefault + " "
781
        //                        + value);
782
        MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " + aName + " "
783
                + type + " " + valueDefault + " " + value, 50);
784
    }
785

    
786
    /**
787
     * SAX Handler that receives notification of internal entity declarations
788
     */
789
    public void internalEntityDecl(String name, String value)
790
            throws org.xml.sax.SAXException
791
    {
792
        //System.out.println("INTERNENTITYDECL: " + name + " " + value);
793
        MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value, 50);
794
    }
795

    
796
    /**
797
     * SAX Handler that receives notification of external entity declarations
798
     */
799
    public void externalEntityDecl(String name, String publicId, String systemId)
800
            throws org.xml.sax.SAXException
801
    {
802
        //System.out.println("EXTERNENTITYDECL: " + name + " " + publicId
803
        //                              + " " + systemId);
804
        MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId
805
                + " " + systemId, 50);
806
        // it processes other external entity, not the DTD;
807
        // it doesn't signal for the DTD here
808
        processingDTD = false;
809
    }
810

    
811
    //
812
    // the next section implements the ErrorHandler interface
813
    //
814

    
815
    /**
816
     * SAX Handler that receives notification of fatal parsing errors
817
     */
818
    public void fatalError(SAXParseException exception) throws SAXException
819
    {
820
        MetaCatUtil.debugMessage("FATALERROR: " + exception.getMessage(), 50);
821
        throw (new SAXException("Fatal processing error.", exception));
822
    }
823

    
824
    /**
825
     * SAX Handler that receives notification of recoverable parsing errors
826
     */
827
    public void error(SAXParseException exception) throws SAXException
828
    {
829
        MetaCatUtil.debugMessage("ERROR: " + exception.getMessage(), 50);
830
        throw (new SAXException("Error in processing EML.", exception));
831
    }
832

    
833
    /**
834
     * SAX Handler that receives notification of warnings
835
     */
836
    public void warning(SAXParseException exception) throws SAXException
837
    {
838
        MetaCatUtil.debugMessage("WARNING: " + exception.getMessage(), 50);
839
        throw (new SAXException("Warning.", exception));
840
    }
841

    
842
    //
843
    // Helper, getter and setter methods
844
    //
845

    
846
    /**
847
     * get the document name
848
     */
849
    public String getDocname()
850
    {
851
        return docname;
852
    }
853

    
854
    /**
855
     * get the document processing state
856
     */
857
    public boolean processingDTD()
858
    {
859
        return processingDTD;
860
    }
861
    
862
    
863
    /**
864
     * get the the is revision doc
865
     * @return
866
     */
867
    public boolean getIsRevisionDoc()
868
    {
869
        return isRevisionDoc;
870
    }
871
    
872
    /**
873
     * Set the the handler is for revisionDoc
874
     * @param isRevisionDoc
875
     */
876
    public void setIsRevisionDoc(boolean isRevisionDoc)
877
    {
878
       this.isRevisionDoc = isRevisionDoc;   
879
    }
880

    
881
    /* Method to write a text buffer for DBSAXNode */
882
    protected long writeTextForDBSAXNode(long previousEndNodeId,
883
            StringBuffer strBuffer, DBSAXNode node) throws SAXException
884
    {
885
        long nodeId = previousEndNodeId;
886
        // Check parameter
887
        if (strBuffer == null || node == null) { return nodeId; }
888
        boolean moredata = true;
889
        String data = null;
890

    
891
        String normalizedData = strBuffer.toString();
892
        strBuffer = new StringBuffer(MetaCatUtil.normalize(normalizedData));
893

    
894
        int bufferSize = strBuffer.length();
895
        int start = 0;
896

    
897
        // if there are some cotent in buffer, write it
898
        if (bufferSize > 0) {
899
            MetaCatUtil.debugMessage("Write text into DB", 50);
900
            // This loop deals with the case where there are more characters
901
            // than can fit in a single database text field (limit is
902
            // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
903
            // write a series of nodes that are MAXDATACHARS long, and then the
904
            // final node contains the remainder
905
            while (moredata) {
906
                bufferSize = strBuffer.length();
907
                if (bufferSize > MAXDATACHARS) {
908
                    data = strBuffer.substring(start, MAXDATACHARS);
909
                    // cut the stringbuffer part that already written into db
910
                    strBuffer = strBuffer.delete(start, MAXDATACHARS);
911
                } else {
912
                    data = strBuffer.substring(start, bufferSize);
913
                    moredata = false;
914
                }
915

    
916
                // Write the content of the node to the database
917
                nodeId = node.writeChildNodeToDB("TEXT", null, data, docid);
918
            }//while
919
        }//if
920
        return nodeId;
921
    }
922
    
923
    public long getRootNodeId()
924
    {
925
        return rootNode.getNodeID();
926
    }
927
    
928
    public String getDocumentType()
929
    {
930
        return doctype;
931
    }
932
    
933
    public String getDocumentName()
934
    {
935
        return docname;
936
    }
937
    
938
    public String getCatalogId()
939
    {
940
        return catalogid;
941
    }
942
}
(23-23/64)