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: sgarg $'
11
 *     '$Date: 2004-12-22 11:46:32 -0800 (Wed, 22 Dec 2004) $'
12
 * '$Revision: 2352 $'
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 systemid;
68

    
69
    private boolean stackCreated = false;
70

    
71
    protected Stack nodeStack;
72

    
73
    protected Vector nodeIndex;
74

    
75
    protected DBConnection connection = null;
76

    
77
    protected DocumentImpl currentDocument;
78

    
79
    protected DBSAXNode rootNode;
80

    
81
    protected String action = null;
82

    
83
    protected String docid = null;
84

    
85
    protected String revision = null;
86

    
87
    protected String user = null;
88

    
89
    protected String[] groups = null;
90

    
91
    protected String pub = null;
92

    
93
    protected Thread xmlIndex;
94

    
95
    private boolean endDocument = false;
96

    
97
    protected int serverCode = 1;
98

    
99
    protected Hashtable namespaces = new Hashtable();
100

    
101
    protected boolean hitTextNode = false; // a flag to hit text node
102

    
103
    // a buffer to keep all text nodes for same element
104
    // it is for element was splited
105
    protected StringBuffer textBuffer = new StringBuffer();
106

    
107
    protected Stack textBufferStack = new Stack();
108

    
109
    protected static final int MAXDATACHARS = 4000;
110

    
111
    //protected static final int MAXDATACHARS = 50;
112
    protected static final long INDEXDELAY = 10000;
113

    
114
    // methods writeChildNodeToDB, setAttribute, setNamespace,
115
    // writeTextForDBSAXNode will increase endNodeId.
116
    protected long endNodeId = -1; // The end node id for a substree
117
    // DOCTITLE attr cleared from the db
118
    //   private static final int MAXTITLELEN = 1000;
119

    
120
    //HandlerTriple stuff
121
    TripleCollection tripleList = new TripleCollection();
122

    
123
    Triple currentTriple = new Triple();
124

    
125
    boolean startParseTriple = false;
126

    
127
    boolean hasTriple = false;
128

    
129
    public static final String ECOGRID = "ecogrid://";
130

    
131
    /**
132
     * Construct an instance of the handler class
133
     *
134
     * @param conn the JDBC connection to which information is written
135
     */
136
    private DBSAXHandler(DBConnection conn)
137
    {
138
        this.connection = conn;
139
        this.atFirstElement = true;
140
        this.processingDTD = false;
141

    
142
        // Create the stack for keeping track of node context
143
        // if it doesn't already exist
144
        if (!stackCreated) {
145
            nodeStack = new Stack();
146
            nodeIndex = new Vector();
147
            stackCreated = true;
148
        }
149
    }
150

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

    
208
    /** SAX Handler that receives notification of beginning of the document */
209
    public void startDocument() throws SAXException
210
    {
211
        MetaCatUtil.debugMessage("start Document", 50);
212

    
213
        // Create the document node representation as root
214
        rootNode = new DBSAXNode(connection, this.docid);
215
        // Add the node to the stack, so that any text data can be
216
        // added as it is encountered
217
        nodeStack.push(rootNode);
218
    }
219

    
220
    /** SAX Handler that receives notification of end of the document */
221
    public void endDocument() throws SAXException
222
    {
223
        MetaCatUtil.debugMessage("end Document", 50);
224
        // Starting new thread for writing XML Index.
225
        // It calls the run method of the thread.
226

    
227
        //if it is data package insert triple into relationtion table;
228
        if (doctype != null
229
                && MetaCatUtil.getOptionList(
230
                        MetaCatUtil.getOption("packagedoctype")).contains(
231
                        doctype) && hasTriple) {
232
            try {
233
                //initial handler and write into relationdb
234
                RelationHandler handler = new RelationHandler(docid, doctype,
235
                        connection, tripleList);
236
            } catch (Exception e) {
237
                MetaCatUtil.debugMessage(
238
                        "Failed to write triples into relation table"
239
                                + e.getMessage(), 30);
240
                throw new SAXException(
241
                        "Failed to write triples into relation table "
242
                                + e.getMessage());
243
            }
244
        }
245
        boolean useXMLIndex =
246
            (new Boolean(MetaCatUtil.getOption("usexmlindex"))).booleanValue();
247
        if (useXMLIndex) {
248
            try {
249
                xmlIndex.start();
250
            } catch (NullPointerException e) {
251
                xmlIndex = null;
252
                throw new SAXException(
253
                        "Problem with starting thread for writing XML Index. "
254
                                + e.getMessage());
255
            }
256
        }
257
    }
258

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

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

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

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

    
282
        // Get a reference to the parent node for the id
283
        try {
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
                MetaCatUtil.debugMessage("DOCNAME-a: " + docname, 30);
318
                MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype, 30);
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
                MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype, 30);
324
            }
325
            rootNode.writeNodename(docname);
326
            try {
327
                // for validated XML Documents store a reference to XML DB
328
                // Catalog
329
                // Because this is select statement and it needn't to roll back
330
                // if
331
                // insert document action fialed.
332
                // In order to decrease DBConnection usage count, we get a new
333
                // dbconnection from pool
334
                String catalogid = null;
335
                DBConnection dbConn = null;
336
                int serialNumber = -1;
337

    
338
                if (systemid != null) {
339
                    try {
340
                        // Get dbconnection
341
                        dbConn = DBConnectionPool
342
                                .getDBConnection("DBSAXHandler.startElement");
343
                        serialNumber = dbConn.getCheckOutSerialNumber();
344

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

    
363
                //create documentImpl object by the constructor which can
364
                // specify
365
                //the revision
366
                currentDocument = new DocumentImpl(connection, rootNode
367
                        .getNodeID(), docname, doctype, docid, revision,
368
                        action, user, this.pub, catalogid, this.serverCode);
369

    
370
            } catch (Exception ane) {
371
                throw (new SAXException("Error in DBSaxHandler.startElement "
372
                        + action, ane));
373
            }
374
        }
375

    
376
        // Create the current node representation
377
        currentNode = new DBSAXNode(connection, qName, localName, parentNode,
378
                currentDocument.getRootNodeID(), docid, currentDocument
379
                        .getDoctype());
380

    
381
        // Add all of the namespaces
382
        String prefix;
383
        String nsuri;
384
        Enumeration prefixes = namespaces.keys();
385
        while (prefixes.hasMoreElements()) {
386
            prefix = (String) prefixes.nextElement();
387
            nsuri = (String) namespaces.get(prefix);
388
            currentNode.setNamespace(prefix, nsuri, docid);
389
        }
390
        namespaces = null;
391
        namespaces = new Hashtable();
392

    
393
        // Add all of the attributes
394
        for (int i = 0; i < atts.getLength(); i++) {
395
            String attributeName = atts.getQName(i);
396
            String attributeValue = atts.getValue(i);
397
            endNodeId = currentNode.setAttribute(attributeName, attributeValue,
398
                    docid);
399

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

    
411
            }
412
        }
413

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

    
430
    /*
431
     * Run a separate thread to build the XML index for this document.  This
432
     * thread is run asynchronously in order to more quickly return control to
433
     * the submitting user.  The run method checks to see if the document has
434
     * been fully inserted before trying to update the xml_index table.
435
     */
436
    public void run()
437
    {
438
        try {
439
            // stop 5 second
440
            Thread.sleep(5000);
441
            //make sure record is done
442
            checkDocumentTable();
443
            // Build the index for this document
444
            currentDocument.buildIndex();
445
        } catch (Exception e) {
446
            MetaCatUtil.debugMessage("Error in DBSAXHandler.run "
447
                    + e.getMessage(), 30);
448
        }
449
    }
450

    
451
    /*
452
     * method to make sure insert is finished before create index table If new
453
     * version of record is in xml_documents every thing will be fine
454
     */
455
    private void checkDocumentTable() throws Exception
456
    {
457

    
458
        DBConnection dbConn = null;
459
        int serialNumber = -1;
460

    
461
        try {
462
            // Opening separate db connection for writing XML Index
463
            dbConn = DBConnectionPool
464
                    .getDBConnection("DBSAXHandler.checkDocumentTable");
465
            serialNumber = dbConn.getCheckOutSerialNumber();
466

    
467
            // the following while loop construct checks to make sure that
468
            // the docid of the document that we are trying to index is already
469
            // in the xml_documents table. if this is not the case, the foreign
470
            // key relationship between xml_documents and xml_index is
471
            // temporarily broken causing multiple problems.
472
            boolean inxmldoc = false;
473
            long startTime = System.currentTimeMillis();
474
            while (!inxmldoc) {
475
                String xmlDocumentsCheck = "select distinct docid from xml_documents"
476
                        + " where docid ='"
477
                        + docid
478
                        + "' and "
479
                        + " rev ='"
480
                        + revision + "'";
481

    
482
                PreparedStatement xmlDocCheck = dbConn
483
                        .prepareStatement(xmlDocumentsCheck);
484
                // Increase usage count
485
                dbConn.increaseUsageCount(1);
486
                xmlDocCheck.execute();
487
                ResultSet doccheckRS = xmlDocCheck.getResultSet();
488
                boolean tableHasRows = doccheckRS.next();
489
                if (tableHasRows) {
490
                    MetaCatUtil.debugMessage(
491
                            "=========== find the correct document", 35);
492
                    inxmldoc = true;
493
                }
494
                doccheckRS.close();
495
                xmlDocCheck.close();
496
                // make sure the while loop will be ended in reseaonable time
497
                long stopTime = System.currentTimeMillis();
498
                if ((stopTime - startTime) > INDEXDELAY) { throw new Exception(
499
                        "Couldn't find the docid for index build in "
500
                                + "reseaonable time!"); }
501
            }//while
502
        } catch (Exception e) {
503
            try {
504
                dbConn.rollback();
505
                //dbconn.close();
506
            } catch (SQLException sqle) {
507
            }
508
            MetaCatUtil.debugMessage("Error in DBSAXHandler.run "
509
                    + e.getMessage(), 30);
510

    
511
        } finally {
512
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
513
        }//finally
514

    
515
    }
516

    
517
    /** SAX Handler that is called for each XML text node */
518
    public void characters(char[] cbuf, int start, int len) throws SAXException
519
    {
520
        MetaCatUtil.debugMessage("CHARACTERS", 50);
521
        // buffer all text nodes for same element. This is for text was splited
522
        // into different nodes
523
        textBuffer.append(new String(cbuf, start, len));
524
        // set hittextnode true
525
        hitTextNode = true;
526
        // if text buffer .size is greater than max, write it to db.
527
        // so we can save memory
528
        if (textBuffer.length() > MAXDATACHARS) {
529
            MetaCatUtil.debugMessage("Write text into DB in charaters"
530
                    + " when text buffer size is greater than maxmum number",
531
                    50);
532
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
533
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
534
                    currentNode);
535
            textBuffer = null;
536
            textBuffer = new StringBuffer();
537
        }
538
    }
539

    
540
    /**
541
     * SAX Handler that is called for each XML text node that is Ignorable
542
     * white space
543
     */
544
    public void ignorableWhitespace(char[] cbuf, int start, int len)
545
            throws SAXException
546
    {
547
        // When validation is turned "on", white spaces are reported here
548
        // When validation is turned "off" white spaces are not reported here,
549
        // but through characters() callback
550
        MetaCatUtil.debugMessage("IGNORABLEWHITESPACE", 50);
551

    
552
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
553
        String data = null;
554
        int leftover = len;
555
        int offset = start;
556
        boolean moredata = true;
557

    
558
        // This loop deals with the case where there are more characters
559
        // than can fit in a single database text field (limit is
560
        // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
561
        // write a series of nodes that are MAXDATACHARS long, and then the
562
        // final node contains the remainder
563
        while (moredata) {
564
            if (leftover > MAXDATACHARS) {
565
                data = new String(cbuf, offset, MAXDATACHARS);
566
                leftover -= MAXDATACHARS;
567
                offset += MAXDATACHARS;
568
            } else {
569
                data = new String(cbuf, offset, leftover);
570
                moredata = false;
571
            }
572

    
573
            // Write the content of the node to the database
574
            endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
575
                    docid);
576
        }
577
    }
578

    
579
    /**
580
     * SAX Handler called once for each processing instruction found: node that
581
     * PI may occur before or after the root element.
582
     */
583
    public void processingInstruction(String target, String data)
584
            throws SAXException
585
    {
586
        MetaCatUtil.debugMessage("PI", 50);
587
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
588
        endNodeId = currentNode.writeChildNodeToDB("PI", target, data, docid);
589
    }
590

    
591
    /** SAX Handler that is called at the end of each XML element */
592
    public void endElement(String uri, String localName, String qName)
593
            throws SAXException
594
    {
595
        MetaCatUtil.debugMessage("End ELEMENT " + qName, 50);
596

    
597
        // write buffered text nodes into db (so no splited)
598
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
599

    
600
        // If before the end element, the parser hit text nodes and store them
601
        // into the buffer, write the buffer to data base. The reason we put
602
        // write database here is for xerces some time split text node
603
        if (hitTextNode) {
604
            MetaCatUtil.debugMessage("Write text into DB in End Element", 50);
605
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
606
                    currentNode);
607

    
608
            //if it is triple parsing process
609
            if (startParseTriple) {
610

    
611
                String content = textBuffer.toString().trim();
612
                if (localName.equals("subject")) { //get the subject content
613
                    currentTriple.setSubject(content);
614
                } else if (localName.equals("relationship")) { //get the
615
                                                               // relationship
616
                                                               // content
617
                    currentTriple.setRelationship(content);
618
                } else if (localName.equals("object")) { //get the object
619
                                                         // content
620
                    currentTriple.setObject(content);
621
                }
622
            }
623

    
624
        }//if
625

    
626
        //set hitText false
627
        hitTextNode = false;
628
        // reset textbuff
629
        textBuffer = null;
630
        textBuffer = new StringBuffer();
631

    
632
        // Get the node from the stack
633
        currentNode = (DBSAXNode) nodeStack.pop();
634
        //finishing parsing single triple
635
        if (startParseTriple && localName.equals("triple")) {
636
            // add trip to triple collection
637
            tripleList.addTriple(currentTriple);
638
            //rest variable
639
            currentTriple = null;
640
            startParseTriple = false;
641
        }
642
    }
643

    
644
    //
645
    // the next section implements the LexicalHandler interface
646
    //
647

    
648
    /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
649
    public void startDTD(String name, String publicId, String systemId)
650
            throws SAXException
651
    {
652
        docname = name;
653
        doctype = publicId;
654
        systemid = systemId;
655

    
656
        processingDTD = true;
657
        DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
658
        //create a DTD node and write docname,publicid and system id into db
659
        // we don't put the dtd node into node stack
660
        DBSAXNode dtdNode = new DBSAXNode(connection, name, publicId, systemId,
661
                currentNode, currentNode.getRootNodeID(), docid);
662
        MetaCatUtil.debugMessage("Start DTD", 50);
663
        MetaCatUtil.debugMessage("Setting processingDTD to true", 50);
664
        MetaCatUtil.debugMessage("DOCNAME: " + docname, 50);
665
        MetaCatUtil.debugMessage("DOCTYPE: " + doctype, 50);
666
        MetaCatUtil.debugMessage("  SYSID: " + systemid, 50);
667
    }
668

    
669
    /**
670
     * SAX Handler that receives notification of end of DTD
671
     */
672
    public void endDTD() throws SAXException
673
    {
674

    
675
        processingDTD = false;
676
        MetaCatUtil.debugMessage("Setting processingDTD to false", 50);
677
        MetaCatUtil.debugMessage("end DTD", 50);
678
    }
679

    
680
    /**
681
     * SAX Handler that receives notification of comments in the DTD
682
     */
683
    public void comment(char[] ch, int start, int length) throws SAXException
684
    {
685
        MetaCatUtil.debugMessage("COMMENT", 50);
686
        if (!processingDTD) {
687
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
688
            endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
689
                    new String(ch, start, length), docid);
690
        }
691
    }
692

    
693
    /**
694
     * SAX Handler that receives notification of the start of CDATA sections
695
     */
696
    public void startCDATA() throws SAXException
697
    {
698
        MetaCatUtil.debugMessage("start CDATA", 50);
699
    }
700

    
701
    /**
702
     * SAX Handler that receives notification of the end of CDATA sections
703
     */
704
    public void endCDATA() throws SAXException
705
    {
706
        MetaCatUtil.debugMessage("end CDATA", 50);
707
    }
708

    
709
    /**
710
     * SAX Handler that receives notification of the start of entities
711
     */
712
    public void startEntity(String name) throws SAXException
713
    {
714
        MetaCatUtil.debugMessage("start ENTITY: " + name, 50);
715
        //System.out.println("start ENTITY: " + name);
716
        if (name.equals("[dtd]")) {
717
            processingDTD = true;
718
        }
719
    }
720

    
721
    /**
722
     * SAX Handler that receives notification of the end of entities
723
     */
724
    public void endEntity(String name) throws SAXException
725
    {
726
        MetaCatUtil.debugMessage("end ENTITY: " + name, 50);
727
        //System.out.println("end ENTITY: " + name);
728
        if (name.equals("[dtd]")) {
729
            processingDTD = false;
730
        }
731
    }
732

    
733
    /**
734
     * SAX Handler that receives notification of element declarations
735
     */
736
    public void elementDecl(String name, String model)
737
            throws org.xml.sax.SAXException
738
    {
739
        //System.out.println("ELEMENTDECL: " + name + " " + model);
740
        MetaCatUtil.debugMessage("ELEMENTDECL: " + name + " " + model, 50);
741
    }
742

    
743
    /**
744
     * SAX Handler that receives notification of attribute declarations
745
     */
746
    public void attributeDecl(String eName, String aName, String type,
747
            String valueDefault, String value) throws org.xml.sax.SAXException
748
    {
749

    
750
        //System.out.println("ATTRIBUTEDECL: " + eName + " "
751
        //                        + aName + " " + type + " " + valueDefault + " "
752
        //                        + value);
753
        MetaCatUtil.debugMessage("ATTRIBUTEDECL: " + eName + " " + aName + " "
754
                + type + " " + valueDefault + " " + value, 50);
755
    }
756

    
757
    /**
758
     * SAX Handler that receives notification of internal entity declarations
759
     */
760
    public void internalEntityDecl(String name, String value)
761
            throws org.xml.sax.SAXException
762
    {
763
        //System.out.println("INTERNENTITYDECL: " + name + " " + value);
764
        MetaCatUtil.debugMessage("INTERNENTITYDECL: " + name + " " + value, 50);
765
    }
766

    
767
    /**
768
     * SAX Handler that receives notification of external entity declarations
769
     */
770
    public void externalEntityDecl(String name, String publicId, String systemId)
771
            throws org.xml.sax.SAXException
772
    {
773
        //System.out.println("EXTERNENTITYDECL: " + name + " " + publicId
774
        //                              + " " + systemId);
775
        MetaCatUtil.debugMessage("EXTERNENTITYDECL: " + name + " " + publicId
776
                + " " + systemId, 50);
777
        // it processes other external entity, not the DTD;
778
        // it doesn't signal for the DTD here
779
        processingDTD = false;
780
    }
781

    
782
    //
783
    // the next section implements the ErrorHandler interface
784
    //
785

    
786
    /**
787
     * SAX Handler that receives notification of fatal parsing errors
788
     */
789
    public void fatalError(SAXParseException exception) throws SAXException
790
    {
791
        MetaCatUtil.debugMessage("FATALERROR: " + exception.getMessage(), 50);
792
        throw (new SAXException("Fatal processing error.", exception));
793
    }
794

    
795
    /**
796
     * SAX Handler that receives notification of recoverable parsing errors
797
     */
798
    public void error(SAXParseException exception) throws SAXException
799
    {
800
        MetaCatUtil.debugMessage("ERROR: " + exception.getMessage(), 50);
801
        throw (new SAXException("Error in processing EML.", exception));
802
    }
803

    
804
    /**
805
     * SAX Handler that receives notification of warnings
806
     */
807
    public void warning(SAXParseException exception) throws SAXException
808
    {
809
        MetaCatUtil.debugMessage("WARNING: " + exception.getMessage(), 50);
810
        throw (new SAXException("Warning.", exception));
811
    }
812

    
813
    //
814
    // Helper, getter and setter methods
815
    //
816

    
817
    /**
818
     * get the document name
819
     */
820
    public String getDocname()
821
    {
822
        return docname;
823
    }
824

    
825
    /**
826
     * get the document processing state
827
     */
828
    public boolean processingDTD()
829
    {
830
        return processingDTD;
831
    }
832

    
833
    /* Method to write a text buffer for DBSAXNode */
834
    protected long writeTextForDBSAXNode(long previousEndNodeId,
835
            StringBuffer strBuffer, DBSAXNode node) throws SAXException
836
    {
837
        long nodeId = previousEndNodeId;
838
        // Check parameter
839
        if (strBuffer == null || node == null) { return nodeId; }
840
        boolean moredata = true;
841
        String data = null;
842

    
843
        String normalizedData = strBuffer.toString();
844
        strBuffer = new StringBuffer(MetaCatUtil.normalize(normalizedData));
845

    
846
        int bufferSize = strBuffer.length();
847
        int start = 0;
848

    
849
        // if there are some cotent in buffer, write it
850
        if (bufferSize > 0) {
851
            MetaCatUtil.debugMessage("Write text into DB", 50);
852
            // This loop deals with the case where there are more characters
853
            // than can fit in a single database text field (limit is
854
            // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
855
            // write a series of nodes that are MAXDATACHARS long, and then the
856
            // final node contains the remainder
857
            while (moredata) {
858
                bufferSize = strBuffer.length();
859
                if (bufferSize > MAXDATACHARS) {
860
                    data = strBuffer.substring(start, MAXDATACHARS);
861
                    // cut the stringbuffer part that already written into db
862
                    strBuffer = strBuffer.delete(start, MAXDATACHARS);
863
                } else {
864
                    data = strBuffer.substring(start, bufferSize);
865
                    moredata = false;
866
                }
867

    
868
                // Write the content of the node to the database
869
                nodeId = node.writeChildNodeToDB("TEXT", null, data, docid);
870
            }//while
871
        }//if
872
        return nodeId;
873
    }
874
}
(23-23/63)