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: Jing Tao
8
 *    Release: @release@
9
 *
10
 *   '$Author: tao $'
11
 *     '$Date: 2005-03-03 15:02:42 -0800 (Thu, 03 Mar 2005) $'
12
 * '$Revision: 2397 $'
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.io.BufferedReader;
32
import java.io.BufferedWriter;
33
import java.io.File;
34
import java.io.FileReader;
35
import java.io.FileWriter;
36
import java.io.IOException;
37
import java.io.Reader;
38
import java.sql.PreparedStatement;
39
import java.sql.ResultSet;
40
import java.sql.SQLException;
41
import java.sql.Statement;
42
import java.util.EmptyStackException;
43
import java.util.Enumeration;
44
import java.util.Hashtable;
45
import java.util.Stack;
46
import java.util.Vector;
47

    
48
import org.xml.sax.Attributes;
49
import org.xml.sax.SAXException;
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
 * Here is the rules for user which has write permission in top level access
55
 * rules(he can update metadata but can't update access module) try to update
56
 * a document:
57
 * 1. Checking access part (both in top level and addtional level, node by node)
58
 *    If something was modified, reject the document. Note: for additional part
59
 *    The access subtree startnode starts at "<describ>" rather than <access>.
60
 *    This is because make sure ids wouldn't be mess up by user.
61
 * 2. Checking ids in additional access part, if they points a distribution
62
 *    module with online or inline. If some ids don't, reject the documents.
63
 * 3. For inline distribution:
64
 *    If user can't read the inline data, the empty string in inline element
65
 *    will be send to user if he read this eml document(user has read access
66
 *    at top level - metadata, but user couldn't read inline data).
67
 *    Here is some intrested senario: If user does have read and write
68
 *    permission in top level access rules(for metadata)
69
 *    but 1) user doesn't have read and write permission in inline data block,
70
 *    so if user update the document with some inline data rather than
71
 *    empty string in same inline data block(same distribution inline id),
72
 *    this means user updated the inline data. So the document should be
73
 *    rejected.
74
 *    2) user doesn't have read permssion, but has write premission in
75
 *    inline data block. If user send back inline data block with empty
76
 *    string, we will think user doesn't update inline data and we will
77
 *    copy old inline data back to the new one. If user send something
78
 *    else, we will overwrite the old inline data by new one.
79
 * 4. For online distribution:
80
 *    It is easy than inline distribution. When the user try to change a external
81
 *    document id, we will checking if the user have "all" permission to it.
82
 *    If don't have, reject the document. If have, delete the old rules and apply
83
 *    The new rules.
84
 *
85
 *
86
 * Here is some info about addtional access rules ( data object rules):
87
 *  The data access rules format looks like:
88
 *  <additionalMetadata>
89
 *    <describes>100</describes>
90
 *    <describes>300</describes>
91
 *    <access>rulesone</access>
92
 *  </additionalMetadata>
93
 *  <additionalMetadata>
94
 *    <describes>200</describes>
95
 *    <access>rulesthree</access>
96
 *  </additionalMetadata>
97
 *  Because eml additionalMetadata is (describes+, any) and any ocurrence is 1.
98
 *  So following xml will be rejected by xerces.
99
 *  <additionalMetadata>
100
 *    <describes>100</describes>
101
 *    <describes>300</describes>
102
 *    <other>....</other>
103
 *    <access>rulesone</access>
104
 *  </additionalMetadata>
105
 */
106
public class Eml200SAXHandler extends DBSAXHandler implements
107
        AccessControlInterface
108
{
109
    private boolean processTopLeverAccess = false;
110

    
111
    // now additionalAccess will be explained as distribution access control
112
    // - data file
113
    private boolean processAdditionalAccess = false;
114

    
115
    private boolean processOtherAccess = false;
116

    
117
    private AccessSection accessObject = null;
118

    
119
    private AccessRule accessRule = null;
120

    
121
    private Vector describesId = new Vector(); // store the ids in
122
                                               //additionalmetadata/describes
123

    
124
    //store all distribution element id for online url. key is the distribution
125
    // id and  data  is url
126
    private Hashtable onlineURLDistributionIdList = new Hashtable();
127
    // distribution/oneline/url will store this vector if distribution doesn't
128
    // have a id.
129
    private Vector onelineURLDistributionListWithoutId = new Vector();
130

    
131
    //store all distribution element id for online other distribution, such as
132
    // connection or connectiondefination. key is the distribution id
133
    // and  data  is distribution id
134
    private Hashtable onlineOtherDistributionIdList = new Hashtable();
135

    
136
    //store all distribution element id for inline data.
137
    // key is the distribution id, data is the internal inline id
138
    private Hashtable inlineDistributionIdList = new Hashtable();
139

    
140
    //store all distribution element id for off line data.
141
    // key is the distribution id, data is the id too.
142
    private Hashtable offlineDistributionIdList = new Hashtable();
143

    
144
    // a hash to stored all distribution id, both key and value are id itself
145
    private Hashtable distributionAllIdList = new Hashtable();
146

    
147
    // temporarily store distribution id
148
    private String distributionId = null;
149

    
150
    // flag to indicate to handle distrubiton
151
    private boolean proccessDistribution = false;
152

    
153
    // a hash table to stored the distribution which is a reference and this
154
    // distribution has a id too. The key is itself id of this distribution,
155
    // the value is the referenced id.
156
    // So, we only stored the format like this:
157
    // <distribution id ="100"><reference>300</reference></distribution>
158
    // the reason is:
159
    // if not id in distribution, then the distribution couldn't be added
160
    // to additional access module. The distribution block which was referenced
161
    // id (300) will be stored in above distribution lists.
162
    private Hashtable distributionReferenceList = new Hashtable();
163

    
164
    private boolean needCheckingAccessModule = false;
165

    
166
    private AccessSection unChangebleTopAccessSubTree = null;
167

    
168
    private Vector unChangebleAdditionalAccessSubTreeVector = new Vector();
169

    
170
    private Hashtable unChangebleReferencedAccessSubTreeHash = new Hashtable();
171

    
172
    private AccessSection topAccessSection;
173

    
174
    private Vector addtionalAccessVector = new Vector();
175

    
176
    // key is subtree id and value is accessSection object
177
    private Hashtable possibleReferencedAccessHash = new Hashtable();
178

    
179
    // we need an another stack to store the access node which we pull out just
180
    // from xml. If a reference happend, we can use the stack the compare nodes
181
    private Stack storedAccessNodeStack = new Stack();
182

    
183
    // vector stored the data file id which will be write into relation table
184
    private Vector onlineDataFileIdInRelationVector = new Vector();
185

    
186
    // Indicator of inline data
187
    private boolean handleInlineData = false;
188

    
189
    private Hashtable inlineDataNameSpace = null;
190

    
191
    private FileWriter inlineDataFileWriter = null;
192

    
193
    private String inlineDataFileName = null;
194

    
195
    private int inLineDataIndex = 0;
196

    
197
    private Vector inlineFileIDList = new Vector();
198

    
199
    private boolean inAddtionalMetaData = false;
200

    
201
    //user has unwritable inline data object when it updates a document
202
    private boolean unWritableInlineDataObject = false;
203
    //user has unreadable inline data when it updates a dcoument
204
    private boolean unReadableInlineDataObject = false;
205

    
206
    // the hashtable contains the info from xml_access table which
207
    // inline data the user can't read when user update a document.
208
    // The key in hashtable is subtree id and data is the inline data internal
209
    // file name.
210

    
211
    private Hashtable previousUnreadableInlineDataObjectHash = new Hashtable();
212

    
213
    // the hashtable contains the info from xml_access table which
214
    // inline data the user can't write when user update a document.
215
    // The key in hashtable is subtree id and data is the inline data internal
216
    // file name.
217
    private Hashtable previousUnwritableInlineDataObjectHash = new Hashtable();
218

    
219
    private Hashtable accessSubTreeAlreadyWriteDBList = new Hashtable();
220

    
221
    //This hashtable will stored the id which already has additional access
222
    // control. So the top level access control will ignore them.
223
    private Hashtable onlineURLIdHasAddtionalAccess   = new Hashtable();
224

    
225
    // additional access module will be in additionalMetadata part. Its format
226
    // look like
227
    //<additionalMetadata>
228
    //   <describes>100</describes>
229
    //   <describes>300</describes>
230
    //   <access>rulesone</access>
231
    //</additionalMetadata>
232
    // If user couldn't have all permission to update access rules, he/she could
233
    // not update access module, but also couldn't update "describes".
234
    // So the start node id for additional access section is the first describes
235
    // element
236
    private boolean firstDescribesInAdditionalMetadata = true;
237
    private long    firstDescribesNodeId               = -1;
238

    
239
    private int numberOfHitUnWritableInlineData = 0;
240

    
241
    // Constant
242
    private static final String EML = "eml";
243

    
244
    private static final String DESCRIBES = "describes";
245

    
246
    private static final String ADDITIONALMETADATA = "additionalMetadata";
247

    
248
    private static final String ORDER = "order";
249

    
250
    private static final String ID = "id";
251

    
252
    private static final String REFERENCES = "references";
253

    
254
    public static final String INLINE = "inline";
255

    
256
    private static final String ONLINE = "online";
257

    
258
    private static final String OFFLINE = "offline";
259

    
260
    private static final String CONNECTION = "connection";
261

    
262
    private static final String CONNECTIONDEFINITION = "connectionDefinition";
263

    
264
    private static final String URL = "url";
265

    
266
    private static final String PERMISSIONERROR = "User try to update a subtree"
267
            + " which it doesn't have write permission!";
268

    
269
    private static final String UPDATEACCESSERROR = "User try to update a "
270
            + "access module which it doesn't have \"ALL\" permission!";
271

    
272
    public static final String TOPLEVEL = "top";
273

    
274
    public static final String DATAACCESSLEVEL = "dataAccess";
275

    
276
    // this level is for the access module which is not in top or additional
277
    // place, but it was referenced by top or additional
278
    private static final String REFERENCEDLEVEL = "referenced";
279

    
280
    private static final String RELATION = "Provides info for";
281

    
282
    private static final String DISTRIBUTION = "distribution";
283

    
284
    /**
285
     * Construct an instance of the handler class In this constructor, user can
286
     * specify the version need to upadate
287
     *
288
     * @param conn the JDBC connection to which information is written
289
     * @param action - "INSERT" or "UPDATE"
290
     * @param docid to be inserted or updated into JDBC connection
291
     * @param revision, the user specified the revision need to be update
292
     * @param user the user connected to MetaCat servlet and owns the document
293
     * @param groups the groups to which user belongs
294
     * @param pub flag for public "read" access on document
295
     * @param serverCode the serverid from xml_replication on which this
296
     *            document resides.
297
     *
298
     */
299
    public Eml200SAXHandler(DBConnection conn, String action, String docid,
300
            String revision, String user, String[] groups, String pub,
301
            int serverCode) throws SAXException
302
    {
303
        super(conn, action, docid, revision, user, groups, pub, serverCode);
304
        // Get the unchangable subtrees (user doesn't have write permission)
305
        try
306
        {
307
            PermissionController control = new PermissionController(docid
308
                    + MetaCatUtil.getOption("accNumSeparator") + revision);
309
            //unChangableSubTreeHash = getUnchangableSubTree(control, user,
310
            // groups);
311

    
312
            //If the action is update and user doesn't have "ALL" permission
313
            // we need to check if user update access subtree
314
            if (action != null && action.equals("UPDATE")
315
                    && !control.hasPermission(user, groups,
316
                            AccessControlInterface.ALLSTRING))
317
            {
318
                needCheckingAccessModule = true;
319
                unChangebleTopAccessSubTree = getTopAccessSubTreeFromDB();
320
                unChangebleAdditionalAccessSubTreeVector =
321
                                         getAdditionalAccessSubTreeListFromDB();
322
                unChangebleReferencedAccessSubTreeHash =
323
                                         getReferencedAccessSubTreeListFromDB();
324
            }
325

    
326
            //Here is for  data object checking.
327
            if (action != null && action.equals("UPDATE"))
328
            {
329
              //info about inline data object which user doesn't have read
330
              //permission the info come from xml_access table
331
              previousUnreadableInlineDataObjectHash = PermissionController.
332
                            getUnReadableInlineDataIdList(docid, user,
333
                                                          groups, true);
334

    
335
              //info about data object which user doesn't have write permission
336
              // the info come from xml_accesss table
337
              previousUnwritableInlineDataObjectHash = PermissionController.
338
                            getUnWritableInlineDataIdList(docid, user,
339
                                                          groups, true);
340

    
341
            }
342

    
343

    
344
        }
345
        catch (Exception e)
346
        {
347
            MetaCatUtil.debugMessage("erorr in Eml200SAXHanlder is "
348
                                     +e.getMessage(), 30);
349
            throw new SAXException(e.getMessage());
350
        }
351
    }
352

    
353
    /*
354
     * Get the top level access subtree info from xml_accesssubtree table.
355
     * If no top access subtree found, null will be return.
356
     */
357
     private AccessSection getTopAccessSubTreeFromDB()
358
                                                       throws SAXException
359
     {
360
       AccessSection topAccess = null;
361
       PreparedStatement pstmt = null;
362
       ResultSet rs = null;
363
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
364
                + "FROM xml_accesssubtree WHERE docid like ? "
365
                + "AND controllevel like ?";
366

    
367

    
368
       try
369
       {
370
            pstmt = connection.prepareStatement(sql);
371
            // Increase DBConnection usage count
372
            connection.increaseUsageCount(1);
373
            // Bind the values to the query
374
            pstmt.setString(1, docid);
375
            pstmt.setString(2, TOPLEVEL);
376
            pstmt.execute();
377

    
378
            // Get result set
379
            rs = pstmt.getResultSet();
380
            if (rs.next())
381
            {
382
                String sectionId = rs.getString(1);
383
                long startNodeId = rs.getLong(2);
384
                long endNodeId = rs.getLong(3);
385
                // create a new access section
386
                topAccess = new AccessSection();
387
                topAccess.setControlLevel(TOPLEVEL);
388
                topAccess.setDocId(docid);
389
                topAccess.setSubTreeId(sectionId);
390
                topAccess.setStartNodeId(startNodeId);
391
                topAccess.setEndNodeId(endNodeId);
392
            }
393
            pstmt.close();
394
        }//try
395
        catch (SQLException e)
396
        {
397
            throw new SAXException(
398
                    "EMLSAXHandler.getTopAccessSubTreeFromDB(): "
399
                            + e.getMessage());
400
        }//catch
401
        finally
402
        {
403
            try
404
            {
405
                pstmt.close();
406
            }
407
            catch (SQLException ee)
408
            {
409
                throw new SAXException(
410
                        "EMLSAXHandler.getTopAccessSubTreeFromDB(): "
411
                                + ee.getMessage());
412
            }
413
        }//finally
414
        return topAccess;
415

    
416
     }
417

    
418
    /*
419
     * Get the subtree node info from xml_accesssubtree table
420
     */
421
    private Vector getAdditionalAccessSubTreeListFromDB() throws Exception
422
    {
423
        Vector result = new Vector();
424
        PreparedStatement pstmt = null;
425
        ResultSet rs = null;
426
        String sql = "SELECT subtreeid, startnodeid, endnodeid "
427
                + "FROM xml_accesssubtree WHERE docid like ? "
428
                + "AND controllevel like ? "
429
                + "ORDER BY startnodeid ASC";
430

    
431
        try
432
        {
433

    
434
            pstmt = connection.prepareStatement(sql);
435
            // Increase DBConnection usage count
436
            connection.increaseUsageCount(1);
437
            // Bind the values to the query
438
            pstmt.setString(1, docid);
439
            pstmt.setString(2, DATAACCESSLEVEL);
440
            pstmt.execute();
441

    
442
            // Get result set
443
            rs = pstmt.getResultSet();
444
            while (rs.next())
445
            {
446
                String sectionId = rs.getString(1);
447
                long startNodeId = rs.getLong(2);
448
                long endNodeId = rs.getLong(3);
449
                // create a new access section
450
                AccessSection accessObj = new AccessSection();
451
                accessObj.setControlLevel(DATAACCESSLEVEL);
452
                accessObj.setDocId(docid);
453
                accessObj.setSubTreeId(sectionId);
454
                accessObj.setStartNodeId(startNodeId);
455
                accessObj.setEndNodeId(endNodeId);
456
                // add this access obj into vector
457
                result.add(accessObj);
458

    
459
            }
460
            pstmt.close();
461
        }//try
462
        catch (SQLException e)
463
        {
464
            throw new SAXException(
465
                    "EMLSAXHandler.getAddtionalAccessSubTreeListFromDB(): "
466
                            + e.getMessage());
467
        }//catch
468
        finally
469
        {
470
            try
471
            {
472
                pstmt.close();
473
            }
474
            catch (SQLException ee)
475
            {
476
                throw new SAXException(
477
                        "EMLSAXHandler.getAccessSubTreeListFromDB(): "
478
                                + ee.getMessage());
479
            }
480
        }//finally
481
        return result;
482
    }
483

    
484
   /*
485
    * Get the access subtree for referenced info from xml_accesssubtree table
486
    */
487
   private Hashtable getReferencedAccessSubTreeListFromDB() throws Exception
488
   {
489
       Hashtable result = new Hashtable();
490
       PreparedStatement pstmt = null;
491
       ResultSet rs = null;
492
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
493
               + "FROM xml_accesssubtree WHERE docid like ? "
494
               + "AND controllevel like ? "
495
               + "ORDER BY startnodeid ASC";
496

    
497
       try
498
       {
499

    
500
           pstmt = connection.prepareStatement(sql);
501
           // Increase DBConnection usage count
502
           connection.increaseUsageCount(1);
503
           // Bind the values to the query
504
           pstmt.setString(1, docid);
505
           pstmt.setString(2, REFERENCEDLEVEL);
506
           pstmt.execute();
507

    
508
           // Get result set
509
           rs = pstmt.getResultSet();
510
           while (rs.next())
511
           {
512
               String sectionId = rs.getString(1);
513
               long startNodeId = rs.getLong(2);
514
               long endNodeId = rs.getLong(3);
515
               // create a new access section
516
               AccessSection accessObj = new AccessSection();
517
               accessObj.setControlLevel(DATAACCESSLEVEL);
518
               accessObj.setDocId(docid);
519
               accessObj.setSubTreeId(sectionId);
520
               accessObj.setStartNodeId(startNodeId);
521
               accessObj.setEndNodeId(endNodeId);
522
               // add this access obj into hastable
523
               if ( sectionId != null && !sectionId.trim().equals(""))
524
               {
525
                 result.put(sectionId, accessObj);
526
               }
527

    
528
           }
529
           pstmt.close();
530
       }//try
531
       catch (SQLException e)
532
       {
533
           throw new SAXException(
534
                   "EMLSAXHandler.getReferencedAccessSubTreeListFromDB(): "
535
                           + e.getMessage());
536
       }//catch
537
       finally
538
       {
539
           try
540
           {
541
               pstmt.close();
542
           }
543
           catch (SQLException ee)
544
           {
545
               throw new SAXException(
546
                       "EMLSAXHandler.getReferencedSubTreeListFromDB(): "
547
                               + ee.getMessage());
548
           }
549
       }//finally
550
       return result;
551
   }
552

    
553

    
554

    
555
    /** SAX Handler that is called at the start of each XML element */
556
    public void startElement(String uri, String localName, String qName,
557
            Attributes atts) throws SAXException
558
    {
559
        // for element <eml:eml...> qname is "eml:eml", local name is "eml"
560
        // for element <acl....> both qname and local name is "eml"
561
        // uri is namesapce
562
        MetaCatUtil.debugMessage("Start ELEMENT(qName) " + qName, 10);
563
        MetaCatUtil.debugMessage("Start ELEMENT(localName) " + localName, 10);
564
        MetaCatUtil.debugMessage("Start ELEMENT(uri) " + uri, 10);
565

    
566
        DBSAXNode parentNode = null;
567
        DBSAXNode currentNode = null;
568
        // none inline part
569
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
570
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
571
        if (!handleInlineData)
572
        {
573
            // Get a reference to the parent node for the id
574
            try
575
            {
576
                parentNode = (DBSAXNode) nodeStack.peek();
577
            }
578
            catch (EmptyStackException e)
579
            {
580
                parentNode = null;
581
            }
582

    
583
            //start handle inline data
584
            //=====================================================
585
            if (qName.equals(INLINE) && !inAddtionalMetaData)
586
            {
587
                handleInlineData = true;
588
                inLineDataIndex++;
589
                //intitialize namespace hash for in line data
590
                inlineDataNameSpace = new Hashtable();
591
                //initialize file writer
592
                String docidWithoutRev = MetaCatUtil.getDocIdFromString(docid);
593
                String seperator = MetaCatUtil.getOption("accNumSeparator");
594
                // the new file name will look like docid.rev.2
595
                inlineDataFileName = docidWithoutRev + seperator + revision
596
                        + seperator + inLineDataIndex;
597
                inlineDataFileWriter = createInlineDataFileWriter(inlineDataFileName);
598
                // put the inline file id into a vector. If upload failed,
599
                // metacat will
600
                // delete the inline data file
601
                inlineFileIDList.add(inlineDataFileName);
602

    
603
                // put distribution id and inline file id into a  hash
604
                if (distributionId != null)
605
                {
606
                  //check to see if this inline data is readable or writable to
607
                  // this user
608
                  if (!previousUnreadableInlineDataObjectHash.isEmpty() &&
609
                       previousUnreadableInlineDataObjectHash.containsKey(distributionId))
610
                  {
611
                      unReadableInlineDataObject = true;
612
                  }
613
                  if (!previousUnwritableInlineDataObjectHash.isEmpty() &&
614
                       previousUnwritableInlineDataObjectHash.containsKey(distributionId))
615
                  {
616
                     unWritableInlineDataObject = true;
617
                     numberOfHitUnWritableInlineData++;
618
                  }
619

    
620

    
621
                  // store the distributid and inlinedata filename into a hash
622
                  inlineDistributionIdList.put(distributionId, inlineDataFileName);
623
                }
624

    
625
            }
626
            //==============================================================
627

    
628

    
629
            // If hit a text node, we need write this text for current's parent
630
            // node
631
            // This will happend if the element is mixted
632
            //==============================================================
633
            if (hitTextNode && parentNode != null)
634
            {
635

    
636

    
637
                if (needCheckingAccessModule
638
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
639
                    // stored the pull out nodes into storedNode stack
640
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
641
                            null, null, MetaCatUtil.normalize(textBuffer
642
                                    .toString()));
643
                    storedAccessNodeStack.push(nodeElement);
644

    
645
                }
646

    
647
                // write the textbuffer into db for parent node.
648
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
649
                        parentNode);
650
                // rest hitTextNode
651
                hitTextNode = false;
652
                // reset textbuffer
653
                textBuffer = null;
654
                textBuffer = new StringBuffer();
655

    
656
            }
657
            //==================================================================
658

    
659
            // Document representation that points to the root document node
660
            //==================================================================
661
            if (atFirstElement)
662
            {
663
                atFirstElement = false;
664
                // If no DOCTYPE declaration: docname = root element
665
                // doctype = root element name or name space
666
                if (docname == null) {
667
                    docname = localName;
668
                    // if uri isn't null doctype = uri(namespace)
669
                    // othewise root element
670
                    if (uri != null && !(uri.trim()).equals("")) {
671
                        doctype = uri;
672
                    } else {
673
                        doctype = docname;
674
                    }
675
                    MetaCatUtil.debugMessage("DOCNAME-a: " + docname, 30);
676
                    MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype, 30);
677
                } else if (doctype == null) {
678
                    // because docname is not null and it is declared in dtd
679
                    // so could not be in schema, no namespace
680
                    doctype = docname;
681
                    MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype, 30);
682
                }
683
                rootNode.writeNodename(docname);
684
                try {
685
                    // for validated XML Documents store a reference to XML DB
686
                    // Catalog
687
                    // Because this is select statement and it needn't to roll
688
                    // back if
689
                    // insert document action fialed.
690
                    // In order to decrease DBConnection usage count, we get a
691
                    // new
692
                    // dbconnection from pool
693
                    String catalogid = null;
694
                    DBConnection dbConn = null;
695
                    int serialNumber = -1;
696

    
697
                    try {
698
                        // Get dbconnection
699
                        dbConn = DBConnectionPool
700
                                .getDBConnection("DBSAXHandler.startElement");
701
                        serialNumber = dbConn.getCheckOutSerialNumber();
702

    
703
                        Statement stmt = dbConn.createStatement();
704
                        ResultSet rs = stmt
705
                                .executeQuery("SELECT catalog_id FROM xml_catalog "
706
                                        + "WHERE entry_type = 'Schema' "
707
                                        + "AND public_id = '" + doctype + "'");
708
                        boolean hasRow = rs.next();
709
                        if (hasRow) {
710
                            catalogid = rs.getString(1);
711
                        }
712
                        stmt.close();
713
                    }//try
714
                    finally {
715
                        // Return dbconnection
716
                        DBConnectionPool.returnDBConnection(dbConn,
717
                                serialNumber);
718
                    }//finally
719

    
720
                    //create documentImpl object by the constructor which can
721
                    // specify
722
                    //the revision
723
                    currentDocument = new DocumentImpl(connection, rootNode
724
                            .getNodeID(), docname, doctype, docid, revision,
725
                            action, user, this.pub, catalogid, this.serverCode);
726

    
727
                } catch (Exception ane) {
728
                    throw (new SAXException(
729
                            "Error in EMLSaxHandler.startElement " + action,
730
                            ane));
731
                }
732
            }
733
            //==================================================================
734

    
735
            // node
736
            //==================================================================
737
            // Create the current node representation
738
            currentNode = new DBSAXNode(connection, qName, localName,
739
                    parentNode, currentDocument.getRootNodeID(), docid,
740
                    currentDocument.getDoctype());
741
            // Use a local variable to store the element node id
742
            // If this element is a start point of subtree(section), it will be
743
            // stored
744
            // otherwise, it will be discated
745
            long startNodeId = currentNode.getNodeID();
746
            // Add all of the namespaces
747
            String prefix = null;
748
            String nsuri = null;
749
            Enumeration prefixes = namespaces.keys();
750
            while (prefixes.hasMoreElements())
751
            {
752
                prefix = (String) prefixes.nextElement();
753
                nsuri = (String) namespaces.get(prefix);
754
                endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
755
            }
756

    
757
            //=================================================================
758
           // attributes
759
           // Add all of the attributes
760
          for (int i = 0; i < atts.getLength(); i++)
761
          {
762
              String attributeName = atts.getQName(i);
763
              String attributeValue = atts.getValue(i);
764
              endNodeId = currentNode.setAttribute(attributeName,
765
                      attributeValue, docid);
766

    
767
              // To handle name space and schema location if the attribute
768
              // name is
769
              // xsi:schemaLocation. If the name space is in not in catalog
770
              // table
771
              // it will be regeistered.
772
              if (attributeName != null
773
                      && attributeName
774
                              .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
775
                  SchemaLocationResolver resolver = new SchemaLocationResolver(
776
                          attributeValue);
777
                  resolver.resolveNameSpace();
778

    
779
              }
780
              else if (attributeName != null && attributeName.equals(ID) &&
781
                       currentNode.getTagName().equals(DISTRIBUTION) &&
782
                       !inAddtionalMetaData)
783
              {
784
                 // this is a distribution element and the id is distributionID
785
                 distributionId = attributeValue;
786
                 distributionAllIdList.put(distributionId, distributionId);
787

    
788
              }
789

    
790
          }//for
791

    
792

    
793
           //=================================================================
794

    
795
            // handle access stuff
796
            //==================================================================
797
            if (localName.equals(ACCESS))
798
            {
799
                //make sure the access is top level
800
                // this mean current node's parent's parent should be "eml"
801
                DBSAXNode tmpNode = (DBSAXNode) nodeStack.pop();// pop out
802
                                                                    // parent
803
                                                                    // node
804
                //peek out grandParentNode
805
                DBSAXNode grandParentNode = (DBSAXNode) nodeStack.peek();
806
                // put parent node back
807
                nodeStack.push(tmpNode);
808
                String grandParentTag = grandParentNode.getTagName();
809
                if (grandParentTag.equals(EML) && !inAddtionalMetaData)
810
                {
811
                  processTopLeverAccess = true;
812

    
813
                }
814
                else if ( !inAddtionalMetaData )
815
                {
816
                  // process other access embedded into resource level
817
                  // module
818
                  processOtherAccess = true;
819
                }
820
                else
821
                {
822
                  // this for access in additional data which don't have
823
                  // described element. If it has a descirbed element,
824
                  // this code would hurt any thing
825
                  processAdditionalAccess = true;
826
                  System.out.println("assing process addtional access true when meet access");
827
                }
828

    
829

    
830
                // create access object
831
                accessObject = new AccessSection();
832
                // set permission order
833
                String permOrder = currentNode.getAttribute(ORDER);
834
                accessObject.setPermissionOrder(permOrder);
835
                // set access id
836
                String accessId = currentNode.getAttribute(ID);
837
                accessObject.setSubTreeId(accessId);
838
                // for additional access subtree, the  start of node id should
839
                // be describe element. We also stored the start access element
840
                // node id too.
841
                if (processAdditionalAccess)
842
                {
843
                  accessObject.seStartedDescribesNodeId(firstDescribesNodeId);
844
                  accessObject.setControlLevel(DATAACCESSLEVEL);
845
                }
846
                else if (processTopLeverAccess)
847
                {
848
                  accessObject.setControlLevel(TOPLEVEL);
849
                }
850
                else if (processOtherAccess)
851
                {
852
                  accessObject.setControlLevel(REFERENCEDLEVEL);
853
                }
854

    
855
                accessObject.setStartNodeId(startNodeId);
856
                accessObject.setDocId(docid);
857

    
858

    
859

    
860
            }
861
            // Set up a access rule for allow
862
            else if (parentNode.getTagName() != null
863
                    && (parentNode.getTagName()).equals(ACCESS)
864
                    && localName.equals(ALLOW))
865
           {
866

    
867
                accessRule = new AccessRule();
868

    
869
                //set permission type "allow"
870
                accessRule.setPermissionType(ALLOW);
871

    
872
            }
873
            // set up an access rule for den
874
            else if (parentNode.getTagName() != null
875
                    && (parentNode.getTagName()).equals(ACCESS)
876
                    && localName.equals(DENY))
877
           {
878
                accessRule = new AccessRule();
879
                //set permission type "allow"
880
                accessRule.setPermissionType(DENY);
881
            }
882

    
883
            //=================================================================
884
            // some other independ stuff
885

    
886
            // Add the node to the stack, so that any text data can be
887
            // added as it is encountered
888
            nodeStack.push(currentNode);
889
            // Add the node to the vector used by thread for writing XML Index
890
            nodeIndex.addElement(currentNode);
891

    
892
            // store access module element and attributes into stored stack
893
            if (needCheckingAccessModule
894
                    && (processAdditionalAccess || processOtherAccess || processTopLeverAccess))
895
            {
896
                // stored the pull out nodes into storedNode stack
897
                NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
898
                        localName, prefix, MetaCatUtil.normalize(null));
899
                storedAccessNodeStack.push(nodeElement);
900
                for (int i = 0; i < atts.getLength(); i++) {
901
                    String attributeName = atts.getQName(i);
902
                    String attributeValue = atts.getValue(i);
903
                    NodeRecord nodeAttribute = new NodeRecord(-2, -2, -2,
904
                            "ATTRIBUTE", attributeName, null, MetaCatUtil
905
                                    .normalize(attributeValue));
906
                    storedAccessNodeStack.push(nodeAttribute);
907
                }
908

    
909
            }
910

    
911
            if (currentNode.getTagName().equals(ADDITIONALMETADATA))
912
            {
913
              inAddtionalMetaData = true;
914
            }
915
            else if (currentNode.getTagName().equals(DESCRIBES) &&
916
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
917
                     firstDescribesInAdditionalMetadata)
918
            {
919
              // this is first decirbes element in additional metadata
920
              firstDescribesNodeId = startNodeId;
921
              // we started process additional access rules here
922
              // because access and describe couldn't be seperated
923
              NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
924
                        localName, prefix, MetaCatUtil.normalize(null));
925
              storedAccessNodeStack.push(nodeElement);
926
              processAdditionalAccess = true;
927
              System.out.println("set processAdditonalAccess ture when meet describe");
928
            }
929
            else if (inAddtionalMetaData && processAdditionalAccess &&
930
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
931
                     !currentNode.getTagName().equals(DESCRIBES) &&
932
                     !currentNode.getTagName().equals(ACCESS))
933
            {
934
               // we start processAddtionalAccess  module when first hit describes
935
               // in additionalMetadata. So this is possible, there are
936
               // "describes" but not "access". So here is try to terminate
937
               // processAddionalAccess. In this situation, there another element
938
               // rather than "describes" or "access" as a child of additionalMetadata
939
               // so this is impossible it will have access element now.
940
               // If additionalMetadata has access element, the flag will be
941
               // terminated in endElement
942
               processAdditionalAccess = false;
943
               System.out.println("set processAddtionAccess false if the there is no access in additional");
944
            }
945
            else if (currentNode.getTagName().equals(DISTRIBUTION) &&
946
                     !inAddtionalMetaData)
947
            {
948
              proccessDistribution = true;
949
            }
950

    
951

    
952
             //==================================================================
953
            // reset name space
954
            namespaces = null;
955
            namespaces = new Hashtable();
956

    
957
        }//not inline data
958
        // inline data
959
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
960
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
961
        else
962
        {
963
            // we don't buffer the inline data in characters() method
964
            // so start character don't need to hand text node.
965

    
966
            // inline data may be the xml format.
967
            StringBuffer inlineElements = new StringBuffer();
968
            inlineElements.append("<").append(qName);
969
            // append attributes
970
            for (int i = 0; i < atts.getLength(); i++) {
971
                String attributeName = atts.getQName(i);
972
                String attributeValue = atts.getValue(i);
973
                inlineElements.append(" ");
974
                inlineElements.append(attributeName);
975
                inlineElements.append("=\"");
976
                inlineElements.append(attributeValue);
977
                inlineElements.append("\"");
978
            }
979
            // append namespace
980
            String prefix = null;
981
            String nsuri = null;
982
            Enumeration prefixes = inlineDataNameSpace.keys();
983
            while (prefixes.hasMoreElements()) {
984
                prefix = (String) prefixes.nextElement();
985
                nsuri =  (String)  inlineDataNameSpace.get(prefix);
986
                inlineElements.append(" ");
987
                inlineElements.append("xmlns:");
988
                inlineElements.append(prefix);
989
                inlineElements.append("=\"");
990
                inlineElements.append(nsuri);
991
                inlineElements.append("\"");
992
            }
993
            inlineElements.append(">");
994
            //reset inline data name space
995
            inlineDataNameSpace = null;
996
            inlineDataNameSpace = new Hashtable();
997
            //write inline data into file
998
            MetaCatUtil.debugMessage("the inline element data is: "
999
                    + inlineElements.toString(), 50);
1000
            writeInlineDataIntoFile(inlineDataFileWriter, inlineElements);
1001
        }//else
1002
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1003
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1004

    
1005
    }
1006

    
1007

    
1008
    /** SAX Handler that is called for each XML text node */
1009
    public void characters(char[] cbuf, int start, int len) throws SAXException
1010
    {
1011
        MetaCatUtil.debugMessage("CHARACTERS", 50);
1012
        if (!handleInlineData) {
1013
            // buffer all text nodes for same element. This is for text was
1014
            // splited
1015
            // into different nodes
1016
            textBuffer.append(new String(cbuf, start, len));
1017
            // set hittextnode true
1018
            hitTextNode = true;
1019
            // if text buffer .size is greater than max, write it to db.
1020
            // so we can save memory
1021
            if (textBuffer.length() >= MAXDATACHARS)
1022
            {
1023
                MetaCatUtil
1024
                        .debugMessage(
1025
                                "Write text into DB in charaters"
1026
                                        + " when text buffer size is greater than maxmum number",
1027
                                50);
1028
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1029
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1030
                        currentNode);
1031
                if (needCheckingAccessModule
1032
                     && (processAdditionalAccess || processOtherAccess || processTopLeverAccess))
1033
                {
1034
                     // stored the pull out nodes into storedNode stack
1035
                     NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1036
                       null, null, MetaCatUtil.normalize(textBuffer
1037
                          .toString()));
1038
                     storedAccessNodeStack.push(nodeElement);
1039

    
1040
                }
1041
                textBuffer = null;
1042
                textBuffer = new StringBuffer();
1043
            }
1044
        }
1045
        else
1046
        {
1047
            // this is inline data and write file system directly
1048
            // we don't need to buffered it.
1049
            StringBuffer inlineText = new StringBuffer();
1050
            inlineText.append(new String(cbuf, start, len));
1051
            MetaCatUtil.debugMessage(
1052
                    "The inline text data write into file system: "
1053
                            + inlineText.toString(), 50);
1054
            writeInlineDataIntoFile(inlineDataFileWriter, inlineText);
1055
        }
1056
    }
1057

    
1058
    /** SAX Handler that is called at the end of each XML element */
1059
    public void endElement(String uri, String localName, String qName)
1060
            throws SAXException
1061
    {
1062
        MetaCatUtil.debugMessage("End ELEMENT " + qName, 50);
1063

    
1064
        // when close inline element
1065
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1066
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1067
        if (localName.equals(INLINE) && handleInlineData)
1068
        {
1069
            // Get the node from the stack
1070
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1071
            String currentTag = currentNode.getTagName();
1072
            MetaCatUtil.debugMessage("End of inline data", 35);
1073
            // close file writer
1074
            try
1075
            {
1076
                inlineDataFileWriter.close();
1077
                handleInlineData = false;
1078
            }
1079
            catch (IOException ioe)
1080
            {
1081
                throw new SAXException(ioe.getMessage());
1082
            }
1083

    
1084
            //check if user changed inine data or not if user doesn't have
1085
            // write permission for this inline block
1086
            // if some error happends, we would delete the inline data file here,
1087
            // we will call a method named deletedInlineFiles in DocumentImple
1088
            if (unWritableInlineDataObject)
1089
            {
1090
                if (unReadableInlineDataObject)
1091
                {
1092
                  // now user just got a empty string in linline part
1093
                  // so if the user send back a empty string is fine and we will
1094
                  // copy the old file to new file. If he send something else,
1095
                  // the document will be rejected
1096
                  if (inlineDataIsEmpty(inlineDataFileName))
1097
                  {
1098
                    copyInlineFile(distributionId, inlineDataFileName);
1099
                  }
1100
                  else
1101
                  {
1102
                    MetaCatUtil.debugMessage(
1103
                               "inline data was changed by a user"
1104
                                       + " who doesn't have permission", 30);
1105
                    throw new SAXException(PERMISSIONERROR);
1106

    
1107
                  }
1108
                }//if
1109
                else
1110
                {
1111
                  // user get the inline data
1112
                  if (modifiedInlineData(distributionId, inlineDataFileName))
1113
                  {
1114
                    MetaCatUtil.debugMessage(
1115
                                "inline data was changed by a user"
1116
                                        + " who doesn't have permission", 30);
1117
                    throw new SAXException(PERMISSIONERROR);
1118
                  }//if
1119
                }//else
1120
            }//if
1121
            else
1122
            {
1123
               //now user can update file.
1124
               if (unReadableInlineDataObject)
1125
               {
1126
                  // now user just got a empty string in linline part
1127
                  // so if the user send back a empty string is fine and we will
1128
                  // copy the old file to new file. If he send something else,
1129
                  // the new inline data will overwite the old one(here we need
1130
                  // do nothing because the new inline data already existed
1131
                  if (inlineDataIsEmpty(inlineDataFileName))
1132
                  {
1133
                    copyInlineFile(distributionId, inlineDataFileName);
1134
                  }
1135
                }//if
1136

    
1137
            }//else
1138
            // put inline data file name into text buffer (without path)
1139
            textBuffer = new StringBuffer(inlineDataFileName);
1140
            // write file name into db
1141
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1142
                    currentNode);
1143
            // reset textbuff
1144
            textBuffer = null;
1145
            textBuffer = new StringBuffer();
1146
            // resetinlinedata file name
1147
            inlineDataFileName = null;
1148
            unWritableInlineDataObject = false;
1149
            unReadableInlineDataObject = false;
1150
            return;
1151
        }
1152
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1153
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1154

    
1155

    
1156

    
1157
        // close element which is not in inline data
1158
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1159
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1160
        if (!handleInlineData)
1161
        {
1162
            // Get the node from the stack
1163
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1164
            String currentTag = currentNode.getTagName();
1165

    
1166
            // If before the end element, the parser hit text nodes and store
1167
            // them
1168
            // into the buffer, write the buffer to data base. The reason we
1169
            // put
1170
            // write database here is for xerces some time split text node
1171
            if (hitTextNode)
1172
            {
1173
                // get access value
1174
                String data = null;
1175
                // add principal
1176
                if (currentTag.equals(PRINCIPAL) && accessRule != null)
1177
                {
1178
                    data = (textBuffer.toString()).trim();
1179
                    accessRule.addPrincipal(data);
1180

    
1181
                }
1182
                else if (currentTag.equals(PERMISSION) && accessRule != null)
1183
                {
1184
                    data = (textBuffer.toString()).trim();
1185
                    // we conbine different a permission into one value
1186
                    int permission = accessRule.getPermission();
1187
                    // add permision
1188
                    if (data.toUpperCase().equals(READSTRING))
1189
                    {
1190
                        permission = permission | READ;
1191
                    }
1192
                    else if (data.toUpperCase().equals(WRITESTRING))
1193
                    {
1194
                        permission = permission | WRITE;
1195
                    }
1196
                    else if (data.toUpperCase().equals(CHMODSTRING))
1197
                    {
1198
                        permission = permission | CHMOD;
1199
                    }
1200
                    else if (data.toUpperCase().equals(ALLSTRING))
1201
                    {
1202
                        permission = permission | ALL;
1203
                    }
1204
                    accessRule.setPermission(permission);
1205
                }
1206
                // put additionalmetadata/describes into vector
1207
                else if (currentTag.equals(DESCRIBES))
1208
                {
1209
                    data = (textBuffer.toString()).trim();
1210
                    describesId.add(data);
1211
                    //firstDescribesInAdditionalMetadata = false;
1212
                    //firstDescribesNodeId = 0;
1213
                }
1214
                else if (currentTag.equals(REFERENCES)
1215
                        && (processTopLeverAccess || processAdditionalAccess || processOtherAccess))
1216
                {
1217
                    // get reference
1218
                    data = (textBuffer.toString()).trim();
1219
                    // put reference id into accessSection
1220
                    accessObject.setReferences(data);
1221

    
1222
                }
1223
                else if (currentTag.equals(REFERENCES) && proccessDistribution)
1224
                {
1225
                  // get reference for distribution
1226
                  data = (textBuffer.toString()).trim();
1227
                  // we only stored the distribution reference which itself
1228
                  // has a id
1229
                  if (distributionId != null)
1230
                  {
1231
                    distributionReferenceList.put(distributionId, data);
1232
                  }
1233

    
1234
                }
1235
                else if (currentTag.equals(URL) && !inAddtionalMetaData)
1236
                {
1237
                    //handle online data, make sure its'parent is online
1238
                    DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1239
                    if (parentNode != null && parentNode.getTagName() != null
1240
                            && parentNode.getTagName().equals(ONLINE))
1241
                    {
1242
                        data = (textBuffer.toString()).trim();
1243
                        if (distributionId != null)
1244
                        {
1245
                          onlineURLDistributionIdList.put(distributionId, data);
1246
                        }
1247
                        else
1248
                        {
1249
                          onelineURLDistributionListWithoutId.add(data);
1250
                        }
1251
                    }//if
1252
                }//else if
1253
                // write text to db if it is not inline data
1254

    
1255
                MetaCatUtil.debugMessage(
1256
                            "Write text into DB in End Element", 50);
1257

    
1258
                 // write text node into db
1259
                 endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1260
                            currentNode);
1261

    
1262
                if (needCheckingAccessModule
1263
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1264
                    // stored the pull out nodes into storedNode stack
1265
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1266
                            null, null, MetaCatUtil.normalize(textBuffer
1267
                                    .toString()));
1268
                    storedAccessNodeStack.push(nodeElement);
1269

    
1270
                }
1271
            }//if handle text node
1272

    
1273

    
1274

    
1275
            //set hitText false
1276
            hitTextNode = false;
1277
            // reset textbuff
1278
            textBuffer = null;
1279
            textBuffer = new StringBuffer();
1280

    
1281

    
1282
            // access stuff
1283
            if (currentTag.equals(ALLOW) || currentTag.equals(DENY))
1284
            {
1285
                // finish parser a ccess rule and assign it to new one
1286
                AccessRule newRule = accessRule;
1287
                //add the new rule to access section object
1288
                accessObject.addAccessRule(newRule);
1289
                // reset access rule
1290
                accessRule = null;
1291
            }// ALLOW or DENY
1292
            else if (currentTag.equals(ACCESS))
1293
            {
1294
                // finish parse a access setction and stored them into different
1295
                // places
1296

    
1297
                accessObject.setEndNodeId(endNodeId);
1298
                AccessSection newAccessObject = accessObject;
1299
                newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
1300
                if (newAccessObject != null)
1301
                {
1302

    
1303
                    if (processTopLeverAccess)
1304
                    {
1305
                       topAccessSection = newAccessObject;
1306

    
1307
                    }//if
1308
                    else if (processAdditionalAccess)
1309
                    {
1310
                        // for additional control
1311
                        // put discribesId into the accessobject and put this
1312
                        // access object into vector
1313
                        newAccessObject.setDescribedIdList(describesId);
1314
                        addtionalAccessVector.add(newAccessObject);
1315

    
1316
                    }//if
1317
                    else if (processOtherAccess)
1318
                    {
1319
                      // we only stored the access object which has a id
1320
                      // because only the access object which has a id can
1321
                      // be reference
1322
                      if (newAccessObject.getSubTreeId() != null &&
1323
                          !newAccessObject.getSubTreeId().trim().equals(""))
1324
                      {
1325
                         possibleReferencedAccessHash.
1326
                           put(newAccessObject.getSubTreeId(), newAccessObject);
1327
                      }
1328
                    }
1329

    
1330
                }//if
1331
                //reset access section object
1332
                accessObject = null;
1333

    
1334
                // reset tmp stored node stack
1335
                storedAccessNodeStack = null;
1336
                storedAccessNodeStack = new Stack();
1337

    
1338
                // reset flag
1339
                processAdditionalAccess = false;
1340
                processTopLeverAccess = false;
1341
                processOtherAccess = false;
1342

    
1343
            }//access element
1344
            else if (currentTag.equals(ADDITIONALMETADATA))
1345
            {
1346
                //reset describesId
1347
                describesId = null;
1348
                describesId = new Vector();
1349
                inAddtionalMetaData = false;
1350
                firstDescribesNodeId = -1;
1351
                // reset tmp stored node stack
1352
                storedAccessNodeStack = null;
1353
                storedAccessNodeStack = new Stack();
1354

    
1355

    
1356
            }
1357
            else if (currentTag.equals(DISTRIBUTION) && !inAddtionalMetaData)
1358
            {
1359
               //reset distribution id
1360
               distributionId = null;
1361
               proccessDistribution = false;
1362
            }
1363
            else if (currentTag.equals(OFFLINE) && !inAddtionalMetaData)
1364
            {
1365
               if (distributionId != null)
1366
               {
1367
                 offlineDistributionIdList.put(distributionId, distributionId);
1368
               }
1369
            }
1370
            else if ((currentTag.equals(CONNECTION) || currentTag.equals(CONNECTIONDEFINITION))
1371
                     && !inAddtionalMetaData)
1372
            {
1373
              //handle online data, make sure its'parent is online
1374
                 DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1375
                 if (parentNode != null && parentNode.getTagName() != null
1376
                         && parentNode.getTagName().equals(ONLINE))
1377
                 {
1378
                     if (distributionId != null)
1379
                     {
1380
                        onlineOtherDistributionIdList.put(distributionId, distributionId);
1381
                     }
1382
                 }//if
1383

    
1384
            }//else if
1385
            else if (currentTag.equals(DESCRIBES))
1386
            {
1387
                firstDescribesInAdditionalMetadata = false;
1388

    
1389
            }
1390

    
1391

    
1392

    
1393
        }
1394
        // close elements which are in inline data (inline data can be xml doc)
1395
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1396
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1397
        else
1398
        {
1399
            // this is in inline part
1400
            StringBuffer endElement = new StringBuffer();
1401
            endElement.append("</");
1402
            endElement.append(qName);
1403
            endElement.append(">");
1404
            MetaCatUtil.debugMessage("inline endElement: "
1405
                    + endElement.toString(), 50);
1406
            writeInlineDataIntoFile(inlineDataFileWriter, endElement);
1407
        }
1408
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1409
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1410
    }
1411

    
1412

    
1413
    /*
1414
     * Method to check if the new line data is as same as the old one
1415
     */
1416
     private boolean modifiedInlineData(String inlineDistributionId,
1417
                                          String newInlineInternalFileName)
1418
     {
1419
       boolean modified = true;
1420
       if (inlineDistributionId == null || newInlineInternalFileName == null)
1421
       {
1422
         return modified;
1423
       }
1424
       String oldInlineInternalFileName =
1425
            (String)previousUnwritableInlineDataObjectHash.get(inlineDistributionId);
1426
       if (oldInlineInternalFileName == null ||
1427
           oldInlineInternalFileName.trim().equals(""))
1428
       {
1429
         return modified;
1430
       }
1431
       MetaCatUtil.debugMessage("in handle inline data", 35);
1432
       MetaCatUtil.debugMessage("the inline data file name from xml_access is: "
1433
                                    + oldInlineInternalFileName, 40);
1434

    
1435
       try
1436
       {
1437
         if (!compareInlineDataFiles(oldInlineInternalFileName,
1438
                                     newInlineInternalFileName))
1439
         {
1440
           modified = true;
1441

    
1442
         }
1443
         else
1444
         {
1445
           modified = false;
1446
         }
1447
       }
1448
       catch(Exception e)
1449
       {
1450
         modified = true;
1451
       }
1452

    
1453
       // delete the inline data file already in file system
1454
       if (modified)
1455
       {
1456
         deleteInlineDataFile(newInlineInternalFileName);
1457

    
1458
       }
1459
       return modified;
1460
     }
1461

    
1462
     /*
1463
      * A method to check if a line file is empty
1464
      */
1465
     private boolean inlineDataIsEmpty(String fileName) throws SAXException
1466
     {
1467
        boolean isEmpty = true;
1468
        if ( fileName == null)
1469
        {
1470
          throw new SAXException("The inline file name is null");
1471
        }
1472
        String path = MetaCatUtil.getOption("inlinedatafilepath");
1473
        // the new file name will look like path/docid.rev.2
1474
        File inlineDataDirectory = new File(path);
1475
        File inlineDataFile = new File(inlineDataDirectory, fileName);
1476
        try
1477
        {
1478
            FileReader inlineFileReader = new FileReader(inlineDataFile);
1479
            BufferedReader inlineStringReader = new BufferedReader(inlineFileReader);
1480
            String string = inlineStringReader.readLine();
1481
            // at the end oldstring will be null
1482
            while (string != null)
1483
            {
1484
                string = inlineStringReader.readLine();
1485
                if (string != null && !string.trim().equals(""))
1486
                {
1487
                  isEmpty = false;
1488
                  break;
1489
                }
1490
            }
1491

    
1492
        }
1493
        catch (Exception e)
1494
        {
1495
            throw new SAXException(e.getMessage());
1496
        }
1497
        return isEmpty;
1498

    
1499
     }
1500

    
1501

    
1502
    /**
1503
     * SAX Handler that receives notification of comments in the DTD
1504
     */
1505
    public void comment(char[] ch, int start, int length) throws SAXException
1506
    {
1507
        MetaCatUtil.debugMessage("COMMENT", 50);
1508
        if (!handleInlineData) {
1509
            if (!processingDTD) {
1510
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1511
                String str = new String(ch, start, length);
1512

    
1513
                //compare comment if need
1514
                /*if (startCriticalSubTree) {
1515
                    compareCommentNode(currentUnChangedableSubtreeNodeStack,
1516
                            str, PERMISSIONERROR);
1517
                }//if*/
1518
                //compare top level access module
1519
                if (processTopLeverAccess && needCheckingAccessModule) {
1520
                    /*compareCommentNode(currentUnchangableAccessModuleNodeStack,
1521
                            str, UPDATEACCESSERROR);*/
1522
                }
1523
                endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
1524
                        str, docid);
1525
                if (needCheckingAccessModule
1526
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1527
                    // stored the pull out nodes into storedNode stack
1528
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2,
1529
                            "COMMENT", null, null, MetaCatUtil.normalize(str));
1530
                    storedAccessNodeStack.push(nodeElement);
1531

    
1532
                }
1533
            }
1534
        } else {
1535
            // inline data comment
1536
            StringBuffer inlineComment = new StringBuffer();
1537
            inlineComment.append("<!--");
1538
            inlineComment.append(new String(ch, start, length));
1539
            inlineComment.append("-->");
1540
            MetaCatUtil.debugMessage("inline data comment: "
1541
                    + inlineComment.toString(), 50);
1542
            writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1543
        }
1544
    }
1545

    
1546

    
1547

    
1548
    /**
1549
     * SAX Handler called once for each processing instruction found: node that
1550
     * PI may occur before or after the root element.
1551
     */
1552
    public void processingInstruction(String target, String data)
1553
            throws SAXException
1554
    {
1555
        MetaCatUtil.debugMessage("PI", 50);
1556
        if (!handleInlineData) {
1557
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1558
            endNodeId = currentNode.writeChildNodeToDB("PI", target, data,
1559
                    docid);
1560
        } else {
1561
            StringBuffer inlinePI = new StringBuffer();
1562
            inlinePI.append("<?");
1563
            inlinePI.append(target);
1564
            inlinePI.append(" ");
1565
            inlinePI.append(data);
1566
            inlinePI.append("?>");
1567
            MetaCatUtil.debugMessage("inline data pi is: "
1568
                    + inlinePI.toString(), 50);
1569
            writeInlineDataIntoFile(inlineDataFileWriter, inlinePI);
1570
        }
1571
    }
1572

    
1573
    /** SAX Handler that is called at the start of Namespace */
1574
    public void startPrefixMapping(String prefix, String uri)
1575
            throws SAXException
1576
    {
1577
        MetaCatUtil.debugMessage("NAMESPACE", 50);
1578
        MetaCatUtil.debugMessage("NAMESPACE prefix "+prefix, 50);
1579
        MetaCatUtil.debugMessage("NAMESPACE uri "+uri, 50);
1580
        if (!handleInlineData) {
1581
            namespaces.put(prefix, uri);
1582
        } else {
1583
            inlineDataNameSpace.put(prefix, uri);
1584
        }
1585
    }
1586

    
1587
    /**
1588
     * SAX Handler that is called for each XML text node that is Ignorable
1589
     * white space
1590
     */
1591
    public void ignorableWhitespace(char[] cbuf, int start, int len)
1592
            throws SAXException
1593
    {
1594
        // When validation is turned "on", white spaces are reported here
1595
        // When validation is turned "off" white spaces are not reported here,
1596
        // but through characters() callback
1597
        MetaCatUtil.debugMessage("IGNORABLEWHITESPACE", 50);
1598
        if (!handleInlineData) {
1599
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1600
            String data = null;
1601
            int leftover = len;
1602
            int offset = start;
1603
            boolean moredata = true;
1604

    
1605
            // This loop deals with the case where there are more characters
1606
            // than can fit in a single database text field (limit is
1607
            // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
1608
            // write a series of nodes that are MAXDATACHARS long, and then the
1609
            // final node contains the remainder
1610
            while (moredata) {
1611
                if (leftover > MAXDATACHARS) {
1612
                    data = new String(cbuf, offset, MAXDATACHARS);
1613
                    leftover -= MAXDATACHARS;
1614
                    offset += MAXDATACHARS;
1615
                } else {
1616
                    data = new String(cbuf, offset, leftover);
1617
                    moredata = false;
1618
                }
1619

    
1620
                //compare whitespace if need
1621
                /*if (startCriticalSubTree) {
1622
                    compareWhiteSpace(currentUnChangedableSubtreeNodeStack,
1623
                            data, PERMISSIONERROR);
1624
                }//if*/
1625

    
1626
                //compare whitespace in access top module
1627
                if (processTopLeverAccess && needCheckingAccessModule) {
1628
                    /*compareWhiteSpace(currentUnchangableAccessModuleNodeStack,
1629
                            data, UPDATEACCESSERROR);*/
1630
                }
1631
                // Write the content of the node to the database
1632
                if (needCheckingAccessModule
1633
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1634
                    // stored the pull out nodes into storedNode stack
1635
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1636
                            null, null, MetaCatUtil.normalize(data));
1637
                    storedAccessNodeStack.push(nodeElement);
1638

    
1639
                }
1640
                endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
1641
                        docid);
1642
            }
1643
        } else {
1644
            //This is inline data write to file directly
1645
            StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf,
1646
                    start, len));
1647
            writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1648
        }
1649

    
1650
    }
1651

    
1652

    
1653
    /** SAX Handler that receives notification of end of the document */
1654
    public void endDocument() throws SAXException
1655
    {
1656
        MetaCatUtil.debugMessage("end Document", 50);
1657
        if (needCheckingAccessModule)
1658
        {
1659
          compareAllAccessModules();
1660
        }
1661

    
1662
        // user deleted some inline block which it counldn't delete
1663
        if (numberOfHitUnWritableInlineData !=
1664
            previousUnwritableInlineDataObjectHash.size())
1665
        {
1666
          throw new SAXException("user deleted some inline block it couldn't");
1667
        }
1668

    
1669
        // write access rule to xml_access table which include both top level
1670
        // and additional level(data access level). It also write access subtree
1671
        // info into xml_accesssubtree about the top access, additional access
1672
        // and some third place access modules which are referenced by top
1673
        // level or additional level
1674
        writeAccessRuleToDB();
1675

    
1676
        //delete relation table
1677
        deleteRelations();
1678
        //write relations
1679
        for (int i = 0; i < onlineDataFileIdInRelationVector.size(); i++) {
1680
            String id = (String) onlineDataFileIdInRelationVector.elementAt(i);
1681
            writeOnlineDataFileIdIntoRelationTable(id);
1682
        }
1683

    
1684
        // clean the subtree record
1685
        accessSubTreeAlreadyWriteDBList = new Hashtable();
1686

    
1687
        // Starting new thread for writing XML Index.
1688
        // It calls the run method of the thread.
1689
        boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
1690
                .booleanValue();
1691
        if (useXMLIndex) {
1692
            try {
1693
                xmlIndex.start();
1694
            } catch (NullPointerException e) {
1695
                xmlIndex = null;
1696
                throw new SAXException(
1697
                        "Problem with starting thread for writing XML Index. "
1698
                                + e.getMessage());
1699
            }
1700
        }
1701
    }
1702

    
1703

    
1704

    
1705
    /* The method will compare all access modules in eml document -
1706
     * topLevel, additionalLevel(data access) and referenced access module*/
1707
    private void compareAllAccessModules() throws SAXException
1708
    {
1709
      //compare top level
1710
      compareAccessSubtree(unChangebleTopAccessSubTree, topAccessSection);
1711

    
1712
      //compare additional level
1713
      int oldSize = unChangebleAdditionalAccessSubTreeVector.size();
1714
      int newSize = addtionalAccessVector.size();
1715
      // if size is different, use deleted or added rules, so throw a exception
1716
      if (oldSize != newSize)
1717
      {
1718
        throw new SAXException(UPDATEACCESSERROR);
1719
      }
1720
      //because access modules are both ordered in ASC in vectors, so we can
1721
      // compare one bye one
1722
      for ( int i = 0; i < newSize; i++)
1723
      {
1724
        AccessSection fromDB = (AccessSection)
1725
                          unChangebleAdditionalAccessSubTreeVector.elementAt(i);
1726
        AccessSection fromParser = (AccessSection)
1727
                                addtionalAccessVector.elementAt(i);
1728
        compareAccessSubtree(fromDB, fromParser);
1729
      }
1730

    
1731
      //compare referenced level
1732
      Enumeration em = unChangebleReferencedAccessSubTreeHash.keys();
1733
      while (em.hasMoreElements())
1734
      {
1735
        String id = (String)em.nextElement();
1736
        AccessSection fromDB = (AccessSection)
1737
                               unChangebleReferencedAccessSubTreeHash.get(id);
1738
        AccessSection fromParser = (AccessSection)
1739
                               possibleReferencedAccessHash.get(id);
1740
        compareAccessSubtree(fromDB, fromParser);
1741
      }
1742
    }
1743

    
1744
    /* The method will compare two access subtree. Currently they compare to
1745
     * nodes one by one. It also can be changed to parse the node first, then
1746
     * compare the parsed result
1747
     */
1748
    private void compareAccessSubtree(AccessSection fromDBTable,
1749
                                       AccessSection fromParser)
1750
                                      throws SAXException
1751
    {
1752
       if (fromDBTable == null || fromParser == null)
1753
       {
1754
         throw new SAXException(UPDATEACCESSERROR);
1755
       }
1756
       Stack nodeStackFromDBTable = fromDBTable.getSubTreeNodeStack();
1757
       Stack nodeStackFromParser  = fromParser.getStoredTmpNodeStack();
1758

    
1759
       Stack tempStack = new Stack();
1760
       while(!nodeStackFromDBTable.isEmpty()){
1761
           tempStack.push(nodeStackFromDBTable.pop());
1762
       }
1763
       comparingNodeStacks(tempStack, nodeStackFromParser);
1764
    }
1765

    
1766
    /* Compare two node stacks to see if they are same */
1767
  private void comparingNodeStacks(Stack stack1, Stack stack2)
1768
          throws SAXException
1769
  {
1770
      // make sure stack1 and stack2 are not empty
1771
      if (stack1.isEmpty() || stack2.isEmpty()) {
1772
          MetaCatUtil.debugMessage("Because stack is empty!", 35);
1773
          throw new SAXException(UPDATEACCESSERROR);
1774
      }
1775
      // go throw two stacks and compare every element
1776
      while (!stack1.isEmpty()) {
1777
          // Pop an element from stack1
1778
          NodeRecord record1 = (NodeRecord) stack1.pop();
1779

    
1780
          // Pop an element from stack2(stack 2 maybe empty)
1781
          NodeRecord record2 = null;
1782
          try {
1783
              record2 = (NodeRecord) stack2.pop();
1784
          } catch (EmptyStackException ee) {
1785

    
1786
              MetaCatUtil.debugMessage(
1787
                      "Node stack2 is empty but stack1 isn't!", 35);
1788
              throw new SAXException(UPDATEACCESSERROR);
1789
          }
1790
          // if two records are not same throw a exception
1791
          if (!record1.contentEquals(record2)) {
1792
              MetaCatUtil
1793
                      .debugMessage(
1794
                              "Two records from new and old stack are not "
1795
                                      + "same!" + record1 + "--" +record2, 30);
1796
              throw new SAXException(UPDATEACCESSERROR);
1797
          }//if
1798
      }//while
1799

    
1800
      // now stack1 is empty and we should make sure stack2 is empty too
1801
      if (!stack2.isEmpty()) {
1802

    
1803
          MetaCatUtil.debugMessage(
1804
                  "stack2 still have some elements while stack1 "
1805
                          + "is empty! ", 30);
1806
          throw new SAXException(UPDATEACCESSERROR);
1807
      }//if
1808
  }//comparingNodeStacks
1809

    
1810

    
1811
    /* The method to write all access rule into db */
1812
    private void writeAccessRuleToDB() throws SAXException
1813
    {
1814
        // delete xml_accesssubtree table record for this docid
1815
        deleteAccessSubTreeRecord(docid);
1816
        //write additional access rule, and old records in xml_access will be
1817
        //deleted too
1818
        System.out.println("before write additional access rules");
1819
        writeAddtionalAccessRuleToDB();
1820
        System.out.println("after write additional access rules");
1821
        //write top leve access rule, and old records in xml_access will be
1822
        //deleted too
1823

    
1824
        if (topAccessSection != null){
1825
          writeTopLevelAccessRuleToDB();
1826
        }
1827
        System.out.println("after write top access rules");
1828
    }//writeAccessRuleToDB
1829

    
1830

    
1831
    /* The method will figure out access reference for given access section -
1832
     * return a new AccessSection which contain access rules that be referenced.
1833
     * And will write the access subtree into xml_access table.
1834
     * this is a recursive method
1835
     */
1836
   private AccessSection resolveAccessRuleReference(AccessSection access)
1837
                                                    throws SAXException
1838
   {
1839
     if (access == null)
1840
     {
1841
       MetaCatUtil.debugMessage("access module is null in " +
1842
                                "resolveAccessRulesReference", 30);
1843
       throw new SAXException("An access modules is null");
1844
     }
1845
     String subTreeId = access.getSubTreeId();
1846
     if (subTreeId == null ||
1847
         (subTreeId != null && !accessSubTreeAlreadyWriteDBList.contains(subTreeId)))
1848
     {
1849
        // we should record this access subtree into accesssubtree table.
1850
        // subtreeId is null means it can't be referenced. So this tree couldn't
1851
        // be stored twise in the table. Subtree is not null, but it is in
1852
        // hash yet, so it is new one.
1853
        writeAccessSubTreeIntoDB(access);
1854
        if (subTreeId != null)
1855
        {
1856
          accessSubTreeAlreadyWriteDBList.put(subTreeId, subTreeId);
1857
        }
1858
     }
1859

    
1860
     String reference = access.getReferences();
1861
     if (reference != null)
1862
     {
1863
       // find the reference in top level
1864
       String topSubtreeId = topAccessSection.getSubTreeId();
1865
       if (topSubtreeId != null && topSubtreeId.equals(reference))
1866
       {
1867
          return resolveAccessRuleReference(topAccessSection);
1868
       }
1869
       else
1870
       {
1871
           // search it the additional access
1872
           for ( int i = 0; i <addtionalAccessVector.size(); i++)
1873
           {
1874
             AccessSection additionalAccess = (AccessSection)
1875
                           addtionalAccessVector.elementAt(i);
1876
             String additionId = additionalAccess.getSubTreeId();
1877
             if (additionId != null && additionId.equals(reference))
1878
             {
1879
               return resolveAccessRuleReference(additionalAccess);
1880
             }// if
1881
           }// for
1882

    
1883
           // search possible referenced access hashtable
1884
           if (possibleReferencedAccessHash.containsKey(reference))
1885
           {
1886
             AccessSection referenceAccess = (AccessSection)
1887
                         possibleReferencedAccessHash.get(reference);
1888
             return resolveAccessRuleReference(referenceAccess);
1889
           }
1890

    
1891
           // if hit here, this means you don't find any id match the reference
1892
           // throw a exception
1893
           throw new SAXException("No access module's id match the reference id");
1894
       }
1895
     }
1896
     else
1897
     {
1898
       // base line reference == null
1899
       AccessSection newAccessSection = new AccessSection();
1900
       access.copyPermOrderAndAccessRules(newAccessSection);
1901
       return newAccessSection;
1902
     }
1903
   }//resolveAccessRuleReference
1904

    
1905
   /* This method will return a id which points a real distribution block if
1906
    *  given a distribution id which is a reference. If the given id is a real
1907
    *  distribution the id itself will be returned.
1908
    *  Here is segment of eml
1909
    *   <distribution id ="100"><online><url>abc</url></online></distribution>
1910
    *   <distribution id ="200"><reference>100</reference></distribution>
1911
    * if the given value is 200, 100 will be returned.
1912
    * if the given value is 100, 100 will be returned.
1913
    */
1914
   private String resolveDistributionReference(String givenId)
1915
   {
1916
      if (givenId == null )
1917
      {
1918
        return null;
1919
      }
1920
      if (!distributionReferenceList.containsKey(givenId))
1921
      {
1922
        //this is not reference distribution block, return given id
1923
        return givenId;
1924
      }
1925
      else
1926
      {
1927
         String referencedId = (String) distributionReferenceList.get(givenId);
1928
         // search util the referenced id is not in dsitribtionReferenceList
1929
         while (distributionReferenceList.containsKey(referencedId))
1930
         {
1931
           referencedId = (String) distributionReferenceList.get(referencedId);
1932
         }
1933
         return referencedId;
1934
      }
1935
   }
1936

    
1937

    
1938
  /* The method to write top level access rule into db. The old rules will be
1939
   * deleted
1940
   * If no describedId in the access object, this access rules will be ingorned
1941
   */
1942
  private void writeAddtionalAccessRuleToDB() throws SAXException
1943
  {
1944
     System.out.println("in write addtional");
1945
     // we should delete all inline access rules in xml_access if
1946
     // user has all permission
1947
     if (!needCheckingAccessModule)
1948
     {
1949
       deleteAllInlineDataAccessRules();
1950
     }
1951
     for (int i=0; i < addtionalAccessVector.size(); i++)
1952
     {
1953
       System.out.println("in for loop of write addtional");
1954
       AccessSection access = (AccessSection)addtionalAccessVector.elementAt(i);
1955
       Vector describeIdList = access.getDescribedIdList();
1956
       // if this access is a reference, a new access object will be created
1957
       // which contains the real access rules referenced. Also, each access tree
1958
       // will be write into xml_accesssubtee table
1959
       AccessSection newAccess = resolveAccessRuleReference(access);
1960
       String permOrder = newAccess.getPermissionOrder();
1961
       Vector accessRule = newAccess.getAccessRules();
1962

    
1963
       if (describeIdList == null || describeIdList.isEmpty())
1964
       {
1965
         continue;
1966
       }
1967

    
1968
       for (int j = 0; j < describeIdList.size(); j++)
1969
       {
1970
         String subreeid = (String)describeIdList.elementAt(j);
1971
         MetaCatUtil.debugMessage("describe id in additional access " +
1972
                                  subreeid, 30);
1973
         // we need to figure out the real id if this subreeid is points to
1974
         // a distribution reference.
1975
         subreeid = resolveDistributionReference(subreeid);
1976
         if (subreeid != null && !subreeid.trim().equals(""))
1977
         {
1978
           MetaCatUtil.debugMessage("subtree id is "+ subreeid +
1979
                                    " after resolve reference id", 30 );
1980
           // if this id is for line data, we need to delete the records first
1981
           // then add new records. The key for deleting is subtee id
1982
           if (inlineDistributionIdList.containsKey(subreeid))
1983
           {
1984
             String inlineFileName = (String)
1985
                                        inlineDistributionIdList.get(subreeid);
1986
             deleteSubtreeAccessRule(subreeid);
1987
             MetaCatUtil.debugMessage("Write inline data access into " +
1988
                                   "xml_access table for"+ inlineFileName, 30);
1989
             writeGivenAccessRuleIntoDB(permOrder, accessRule,
1990
                                        inlineFileName, subreeid);
1991
           }
1992
           else if (onlineURLDistributionIdList.containsKey(subreeid))
1993
           {
1994
             String url = (String)onlineURLDistributionIdList.get(subreeid);
1995
             //this method will extrace data file id from url. It also will
1996
             // check if user can change the access rules for the data file id.
1997
             // if couldn't, it will throw a exception. Morover, the docid will
1998
             // be to relation id vector too.
1999
             // for online data, the subtree id we set is null.
2000
             // So in xml_access, only the inline data subteeid is not null
2001
             String dataFileName = handleOnlineUrlDataFile(url);
2002
             MetaCatUtil.debugMessage("The data fileName in online url " +
2003
                                      dataFileName, 30);
2004
             if (dataFileName != null)
2005
             {
2006
               deletePermissionsInAccessTableForDoc(dataFileName);
2007
               writeGivenAccessRuleIntoDB(permOrder, accessRule,
2008
                                          dataFileName, null);
2009
               MetaCatUtil.debugMessage("Write online data access into " +
2010
                                   "xml_access table for " + dataFileName, 30);
2011
               // put the id into a hashtalbe. So when we run wirtetop level
2012
               // access, those id will be ignored because they already has
2013
               // additional access rules
2014
               onlineURLIdHasAddtionalAccess.put(subreeid, subreeid);
2015
             }
2016
           }//elseif
2017
         }//if
2018
       }//for
2019
     }//for
2020

    
2021
   }//writeAdditonalLevelAccessRuletoDB
2022

    
2023

    
2024
    /* The method to write addtional access rule into db. */
2025
    private void writeTopLevelAccessRuleToDB() throws SAXException
2026
    {
2027
       // if top access is reference, we need figure out the real access rules
2028
       // it points to
2029
       System.out.println("permorder in top level" + topAccessSection.getPermissionOrder());
2030
       AccessSection newAccess = resolveAccessRuleReference(topAccessSection);
2031
       System.out.println("permorder in new level" + newAccess.getPermissionOrder());
2032
       String permOrder = newAccess.getPermissionOrder();
2033
       Vector accessRule = newAccess.getAccessRules();
2034
       String subtree     = null;
2035
       // document itself
2036
       deletePermissionsInAccessTableForDoc(docid);
2037
       writeGivenAccessRuleIntoDB(permOrder, accessRule, docid, subtree);
2038
       // for online data, it includes with id and without id.
2039
       // 1. for the data with subtree id, we should ignore the ones already in
2040
       // the hash - onlineURLIdHasAddionalAccess.
2041
       // 2. for those without subreeid, it couldn't have additional access and we
2042
       // couldn't ignore it.
2043
       // 3. for inline data, we need do nothing because if it doesn't have
2044
       // additional access, it default value is the top one.
2045

    
2046
       // here is the online url with id
2047
       Enumeration em = onlineURLDistributionIdList.keys();
2048
       while (em.hasMoreElements())
2049
       {
2050
         String onlineSubtreeId = (String)em.nextElement();
2051
         if (!onlineURLIdHasAddtionalAccess.containsKey(onlineSubtreeId))
2052
         {
2053
            String url =
2054
                       (String)onlineURLDistributionIdList.get(onlineSubtreeId);
2055
            String onlineDataId = handleOnlineUrlDataFile(url);
2056
            if (onlineDataId != null)
2057
            {
2058
              deletePermissionsInAccessTableForDoc(onlineDataId);
2059
              writeGivenAccessRuleIntoDB(permOrder, accessRule,
2060
                                         onlineDataId, subtree);
2061
            }
2062

    
2063
         }
2064
       }//while
2065

    
2066
       // here is the onlineURL without id
2067
       for (int i= 0; i < onelineURLDistributionListWithoutId.size(); i++)
2068
       {
2069
         String url = (String)onelineURLDistributionListWithoutId.elementAt(i);
2070
         String onlineDataId = handleOnlineUrlDataFile(url);
2071
         if (onlineDataId != null)
2072
         {
2073
           deletePermissionsInAccessTableForDoc(onlineDataId);
2074
           writeGivenAccessRuleIntoDB(permOrder, accessRule,
2075
                                         onlineDataId, subtree);
2076
         }
2077
       }//for
2078
    }//writeTopAccessRuletoDB
2079

    
2080
    /* Write a gaven access rule into db */
2081
    private void writeGivenAccessRuleIntoDB(String permOrder, Vector accessRules,
2082
                     String dataId, String subTreeId) throws SAXException
2083
    {
2084
      if (permOrder == null || permOrder.trim().equals("") || dataId == null ||
2085
          dataId.trim().equals("") || accessRules == null ||
2086
          accessRules.isEmpty())
2087
      {
2088
        MetaCatUtil.debugMessage("The access object is null and tried to " +
2089
                                  " write to xml_access table", 30);
2090
        throw new SAXException("The access object is null");
2091
      }
2092
       // get rid of rev from dataId
2093
       //dataId = MetaCatUtil.getDocIdFromString(dataId);
2094
       //String permOrder = accessSection.getPermissionOrder();
2095
       String sql = null;
2096
       PreparedStatement pstmt = null;
2097
       sql = "INSERT INTO xml_access (docid, principal_name, permission, "
2098
               + "perm_type, perm_order, accessfileid, subtreeid) VALUES "
2099
               + " (?, ?, ?, ?, ?, ?, ?)";
2100

    
2101
       try
2102
       {
2103

    
2104
           pstmt = connection.prepareStatement(sql);
2105
           // Increase DBConnection usage count
2106
           connection.increaseUsageCount(1);
2107
           // Bind the values to the query
2108
           pstmt.setString(1, dataId);
2109
           MetaCatUtil.debugMessage("Docid in accesstable: " + docid, 35);
2110
           pstmt.setString(6, docid);
2111
           MetaCatUtil.debugMessage("Accessfileid in accesstable: " + docid,
2112
                   35);
2113
           pstmt.setString(5, permOrder);
2114
           MetaCatUtil.debugMessage("PermOder in accesstable: " + permOrder,
2115
                   35);
2116
           pstmt.setString(7, subTreeId);
2117
           MetaCatUtil.debugMessage("subtree id in accesstable: " + subTreeId,
2118
                   35);
2119
           // if it is not top level, set s id
2120

    
2121
           //Vector accessRules = accessSection.getAccessRules();
2122
           // go through every rule
2123
           for (int i = 0; i < accessRules.size(); i++)
2124
           {
2125
               AccessRule rule = (AccessRule) accessRules.elementAt(i);
2126
               String permType = rule.getPermissionType();
2127
               int permission = rule.getPermission();
2128
               pstmt.setInt(3, permission);
2129
               MetaCatUtil.debugMessage("permission in accesstable: "
2130
                       + permission, 35);
2131
               pstmt.setString(4, permType);
2132
               MetaCatUtil.debugMessage(
2133
                       "Permtype in accesstable: " + permType, 35);
2134
               // go through every principle in rule
2135
               Vector nameVector = rule.getPrincipal();
2136
               for (int j = 0; j < nameVector.size(); j++)
2137
               {
2138
                   String prName = (String) nameVector.elementAt(j);
2139
                   pstmt.setString(2, prName);
2140
                   MetaCatUtil.debugMessage("Principal in accesstable: "
2141
                           + prName, 35);
2142
                   pstmt.execute();
2143
               }//for
2144
           }//for
2145
           pstmt.close();
2146
       }//try
2147
       catch (SQLException e)
2148
       {
2149
           throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
2150
                   + e.getMessage());
2151
       }//catch
2152
       finally
2153
       {
2154
           try
2155
           {
2156
               pstmt.close();
2157
           }
2158
           catch (SQLException ee)
2159
           {
2160
               throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
2161
                       + ee.getMessage());
2162
           }
2163
       }//finally
2164

    
2165
    }//writeGivenAccessRuleIntoDB
2166

    
2167

    
2168
    /* Delete from db all permission for resources related to @docid if any. */
2169
    private void deletePermissionsInAccessTableForDoc(String docid)
2170
            throws SAXException
2171
    {
2172
        Statement stmt = null;
2173
        try {
2174
            // delete all acl records for resources related to @aclid if any
2175
            stmt = connection.createStatement();
2176
            // Increase DBConnection usage count
2177
            connection.increaseUsageCount(1);
2178
            stmt.execute("DELETE FROM xml_access WHERE docid = '"
2179
                    + docid + "'");
2180

    
2181
        } catch (SQLException e) {
2182
            throw new SAXException(e.getMessage());
2183
        } finally {
2184
            try {
2185
                stmt.close();
2186
            } catch (SQLException ee) {
2187
                throw new SAXException(ee.getMessage());
2188
            }
2189
        }
2190
    }//deletePermissionsInAccessTable
2191

    
2192
    /* Delete access rules from xml_access for a subtee id */
2193
    private void deleteSubtreeAccessRule(String subtreeid) throws SAXException
2194
    {
2195
      Statement stmt = null;
2196
       try
2197
       {
2198
           stmt = connection.createStatement();
2199
           // Increase DBConnection usage count
2200
           connection.increaseUsageCount(1);
2201
           stmt.execute("DELETE FROM xml_access WHERE accessfileid = '"
2202
                   + docid + "' AND subtreeid ='" + subtreeid +"'");
2203
       }
2204
       catch (SQLException e)
2205
       {
2206
           throw new SAXException(e.getMessage());
2207
       }
2208
       finally
2209
       {
2210
           try
2211
           {
2212
               stmt.close();
2213
           }
2214
           catch (SQLException ee)
2215
           {
2216
               throw new SAXException(ee.getMessage());
2217
           }
2218
       }
2219

    
2220
    }
2221

    
2222
    private void deleteAllInlineDataAccessRules() throws SAXException
2223
    {
2224
      Statement stmt = null;
2225
       try
2226
       {
2227
           stmt = connection.createStatement();
2228
           // Increase DBConnection usage count
2229
           connection.increaseUsageCount(1);
2230
           stmt.execute("DELETE FROM xml_access WHERE accessfileid = '"
2231
                   + docid + "' AND subtreeid IS NOT NULL");
2232
       }
2233
       catch (SQLException e)
2234
       {
2235
           throw new SAXException(e.getMessage());
2236
       }
2237
       finally
2238
       {
2239
           try
2240
           {
2241
               stmt.close();
2242
           }
2243
           catch (SQLException ee)
2244
           {
2245
               throw new SAXException(ee.getMessage());
2246
           }
2247
       }
2248

    
2249
    }
2250

    
2251
    /*
2252
     * In order to make sure only usr has "all" permission can update access
2253
     * subtree in eml document we need to keep access subtree info in
2254
     * xml_accesssubtree table, such as docid, version, startnodeid, endnodeid
2255
     */
2256
    private void writeAccessSubTreeIntoDB(AccessSection accessSection)
2257
                                          throws SAXException
2258
    {
2259
        if (accessSection == null)
2260
        {
2261

    
2262
          MetaCatUtil.debugMessage("Access object is null and tried to write "+
2263
                                   "into access subtree table", 30);
2264
          throw new SAXException("The access object is null to write access " +
2265
                                 "sbutree");
2266
        }
2267

    
2268
        String sql = null;
2269
        PreparedStatement pstmt = null;
2270
        sql = "INSERT INTO xml_accesssubtree (docid, rev, controllevel, "
2271
                + "subtreeid, startnodeid, endnodeid) VALUES "
2272
                + " (?, ?, ?, ?, ?, ?)";
2273
        try
2274
        {
2275

    
2276
            pstmt = connection.prepareStatement(sql);
2277
            // Increase DBConnection usage count
2278
            connection.increaseUsageCount(1);
2279
            String level = accessSection.getControlLevel();
2280
            long startNodeId = -1;
2281
            if (level != null && level.equals(DATAACCESSLEVEL))
2282
            {
2283
              // for addtional access module the start node id should be
2284
              // descirbes element id
2285
              startNodeId = accessSection.getStartedDescribesNodeId();
2286
              // if in additional access, there is not describes element,
2287
              // in this senario, describesNodeId will be -1. Then we should
2288
              // the start access element id
2289
              if (startNodeId == -1)
2290
              {
2291
                startNodeId = accessSection.getStartNodeId();
2292
              }
2293
            }
2294
            else
2295
            {
2296
                startNodeId = accessSection.getStartNodeId();
2297
            }
2298

    
2299
            long endNodeId = accessSection.getEndNodeId();
2300
            String sectionId = accessSection.getSubTreeId();
2301

    
2302
            if (startNodeId ==-1 || endNodeId == -1)
2303
            {
2304
              throw new SAXException("Don't find start node or end node id " +
2305
                                      "for the access subtee");
2306

    
2307
            }
2308

    
2309
            // Bind the values to the query
2310
            pstmt.setString(1, docid);
2311
            MetaCatUtil.debugMessage("Docid in access-subtreetable: " + docid,
2312
                    35);
2313
            pstmt.setString(2, revision);
2314
            MetaCatUtil.debugMessage("rev in accesssubtreetable: " + revision,
2315
                    35);
2316
            pstmt.setString(3, level);
2317
            MetaCatUtil.debugMessage("contorl level in access-subtree table: "
2318
                    + level, 35);
2319
            pstmt.setString(4, sectionId);
2320
            MetaCatUtil.debugMessage("Subtree id in access-subtree table: "
2321
                    + sectionId, 35);
2322
            pstmt.setLong(5, startNodeId);
2323
            MetaCatUtil.debugMessage("Start node id is: " + startNodeId, 35);
2324
            pstmt.setLong(6, endNodeId);
2325
            MetaCatUtil.debugMessage("End node id is: " + endNodeId, 35);
2326
            pstmt.execute();
2327
            pstmt.close();
2328
        }//try
2329
        catch (SQLException e)
2330
        {
2331
            throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2332
                    + e.getMessage());
2333
        }//catch
2334
        finally
2335
        {
2336
            try
2337
            {
2338
                pstmt.close();
2339
            }
2340
            catch (SQLException ee)
2341
            {
2342
                throw new SAXException(
2343
                        "EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2344
                                + ee.getMessage());
2345
            }
2346
        }//finally
2347

    
2348
    }//writeAccessSubtreeIntoDB
2349

    
2350
    /* Delete every access subtree record from xml_accesssubtree. */
2351
    private void deleteAccessSubTreeRecord(String docId) throws SAXException
2352
    {
2353
        Statement stmt = null;
2354
        try {
2355
            // delete all acl records for resources related to @aclid if any
2356
            stmt = connection.createStatement();
2357
            // Increase DBConnection usage count
2358
            connection.increaseUsageCount(1);
2359
            stmt.execute("DELETE FROM xml_accesssubtree WHERE docid = '"
2360
                    + docId + "'");
2361

    
2362
        } catch (SQLException e) {
2363
            throw new SAXException(e.getMessage());
2364
        } finally {
2365
            try {
2366
                stmt.close();
2367
            } catch (SQLException ee) {
2368
                throw new SAXException(ee.getMessage());
2369
            }
2370
        }
2371
    }//deleteAccessSubTreeRecord
2372

    
2373
    // open a file writer for writing inline data to file
2374
    private FileWriter createInlineDataFileWriter(String fileName)
2375
            throws SAXException
2376
    {
2377
        FileWriter writer = null;
2378
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2379
        /*
2380
         * File inlineDataDirectory = new File(path);
2381
         */
2382
        String newFile = path + "/" + fileName;
2383
        MetaCatUtil.debugMessage("inline file name: " + newFile, 30);
2384
        try {
2385
            // true means append
2386
            writer = new FileWriter(newFile, true);
2387
        } catch (IOException ioe) {
2388
            throw new SAXException(ioe.getMessage());
2389
        }
2390
        return writer;
2391
    }
2392

    
2393
    // write inline data into file system and return file name(without path)
2394
    private void writeInlineDataIntoFile(FileWriter writer, StringBuffer data)
2395
            throws SAXException
2396
    {
2397
        try {
2398
            writer.write(data.toString());
2399
            writer.flush();
2400
        } catch (Exception e) {
2401
            throw new SAXException(e.getMessage());
2402
        }
2403
    }
2404

    
2405

    
2406

    
2407
    /*
2408
     * In eml2, the inline data wouldn't store in db, it store in file system
2409
     * The db stores file name(without path). We got the old file name from db
2410
     * and compare to the new in line data file
2411
     */
2412
    public boolean compareInlineDataFiles(String oldFileName, String newFileName)
2413
            throws McdbException
2414
    {
2415
        // this method need to be testing
2416
        boolean same = true;
2417
        String data = null;
2418
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2419
        // the new file name will look like path/docid.rev.2
2420
        File inlineDataDirectory = new File(path);
2421
        File oldDataFile = new File(inlineDataDirectory, oldFileName);
2422
        File newDataFile = new File(inlineDataDirectory, newFileName);
2423
        try {
2424
            FileReader oldFileReader = new FileReader(oldDataFile);
2425
            BufferedReader oldStringReader = new BufferedReader(oldFileReader);
2426
            FileReader newFileReader = new FileReader(newDataFile);
2427
            BufferedReader newStringReader = new BufferedReader(newFileReader);
2428
            // read first line of data
2429
            String oldString = oldStringReader.readLine();
2430
            String newString = newStringReader.readLine();
2431

    
2432
            // at the end oldstring will be null
2433
            while (oldString != null) {
2434
                oldString = oldStringReader.readLine();
2435
                newString = newStringReader.readLine();
2436
                if (!oldString.equals(newString)) {
2437
                    same = false;
2438
                    break;
2439
                }
2440
            }
2441

    
2442
            // if oldString is null but newString is not null, they are same
2443
            if (same) {
2444
                if (newString != null) {
2445
                    same = false;
2446
                }
2447
            }
2448

    
2449
        } catch (Exception e) {
2450
            throw new McdbException(e.getMessage());
2451
        }
2452
        MetaCatUtil.debugMessage("the inline data retrieve from file: " + data,
2453
                50);
2454
        return same;
2455
    }
2456

    
2457
   /*
2458
    * Copy a old line file to a new inline file
2459
    */
2460
   public void copyInlineFile(String inlineDistributionId, String newFileName)
2461
           throws SAXException
2462
   {
2463
     if (inlineDistributionId == null || newFileName == null)
2464
     {
2465
       throw new SAXException("Could not copy inline file from old one to new "+
2466
                              "one!");
2467
     }
2468
     // get old file id from previousUnreadable data object
2469
    String oldInlineInternalFileName =
2470
         (String)previousUnreadableInlineDataObjectHash.get(inlineDistributionId);
2471

    
2472
    if (oldInlineInternalFileName == null ||
2473
        oldInlineInternalFileName.trim().equals(""))
2474
    {
2475
      throw new SAXException("Could not copy inline file from old one to new "+
2476
                              "one because can't find old file name");
2477
    }
2478
    MetaCatUtil.debugMessage("in handle inline data", 35);
2479
    MetaCatUtil.debugMessage("the inline data file name from xml_access is: "
2480
                                 + oldInlineInternalFileName, 40);
2481

    
2482
    String path = MetaCatUtil.getOption("inlinedatafilepath");
2483
    // the new file name will look like path/docid.rev.2
2484
    File inlineDataDirectory = new File(path);
2485
    File oldDataFile = new File(inlineDataDirectory, oldInlineInternalFileName);
2486
    File newDataFile = new File(inlineDataDirectory, newFileName);
2487
    FileReader oldFileReader = null;
2488
    FileWriter newFileWriter = null;
2489
    try
2490
    {
2491
      oldFileReader = new FileReader(oldDataFile);
2492
      newFileWriter = new FileWriter(newDataFile);
2493
      char[] buf = new char[4 * 1024]; // 4K buffer
2494
      int b = oldFileReader.read(buf);
2495
      while (b != -1)
2496
      {
2497
        newFileWriter.write(buf, 0, b);
2498
        b = oldFileReader.read(buf);
2499

    
2500
      }
2501
    }
2502
    catch (Exception e)
2503
    {
2504
      throw new SAXException(e.getMessage());
2505
    }
2506
    finally
2507
    {
2508
        if (oldFileReader != null)
2509
        {
2510
          try
2511
          {
2512
            oldFileReader.close();
2513
          }
2514
          catch (Exception ee)
2515
          {
2516
            throw new SAXException(ee.getMessage());
2517
          }
2518

    
2519
        }
2520
        if (newFileWriter != null)
2521
        {
2522
          try
2523
          {
2524
            newFileWriter.close();
2525
          }
2526
          catch (Exception ee)
2527
          {
2528
            throw new SAXException(ee.getMessage());
2529
          }
2530

    
2531
        }
2532

    
2533
    }
2534

    
2535
  }
2536

    
2537

    
2538
    // if xml file failed to upload, we need to call this method to delete
2539
    // the inline data already in file system
2540
    public void deleteInlineFiles()
2541
    {
2542
        if (!inlineFileIDList.isEmpty()) {
2543
            for (int i = 0; i < inlineFileIDList.size(); i++) {
2544
                String fileName = (String) inlineFileIDList.elementAt(i);
2545
                deleteInlineDataFile(fileName);
2546
            }
2547
        }
2548
    }
2549

    
2550
    /* delete the inline data file */
2551
    private void deleteInlineDataFile(String fileName)
2552
    {
2553

    
2554
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2555
        File inlineDataDirectory = new File(path);
2556
        File newFile = new File(inlineDataDirectory, fileName);
2557
        newFile.delete();
2558

    
2559
    }
2560

    
2561
    /*
2562
     * In eml2, the inline data wouldn't store in db, it store in file system
2563
     * The db stores file name(without path).
2564
     */
2565
    public static Reader readInlineDataFromFileSystem(String fileName)
2566
            throws McdbException
2567
    {
2568
        //BufferedReader stringReader = null;
2569
        FileReader fileReader = null;
2570
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2571
        // the new file name will look like path/docid.rev.2
2572
        File inlineDataDirectory = new File(path);
2573
        File dataFile = new File(inlineDataDirectory, fileName);
2574
        try {
2575
            fileReader = new FileReader(dataFile);
2576
            //stringReader = new BufferedReader(fileReader);
2577
        } catch (Exception e) {
2578
            throw new McdbException(e.getMessage());
2579
        }
2580
        // return stringReader;
2581
        return fileReader;
2582
    }
2583

    
2584
    /* Delete relations */
2585
    private void deleteRelations() throws SAXException
2586
    {
2587
        PreparedStatement pStmt = null;
2588
        String sql = "DELETE FROM xml_relation where docid =?";
2589
        try {
2590
            pStmt = connection.prepareStatement(sql);
2591
            //bind variable
2592
            pStmt.setString(1, docid);
2593
            //execute query
2594
            pStmt.execute();
2595
            pStmt.close();
2596
        }//try
2597
        catch (SQLException e) {
2598
            throw new SAXException("EMLSAXHandler.deleteRelations(): "
2599
                    + e.getMessage());
2600
        }//catch
2601
        finally {
2602
            try {
2603
                pStmt.close();
2604
            }//try
2605
            catch (SQLException ee) {
2606
                throw new SAXException("EMLSAXHandler.deleteRelations: "
2607
                        + ee.getMessage());
2608
            }//catch
2609
        }//finally
2610
    }
2611

    
2612
    /* Write an online data file id into xml_relation table. The dataId shouldnot
2613
     * have the revision
2614
     */
2615
    private void writeOnlineDataFileIdIntoRelationTable(String dataId)
2616
            throws SAXException
2617
    {
2618
        PreparedStatement pStmt = null;
2619
        String sql = "INSERT into xml_relation (docid, packagetype, subject, "
2620
                + "relationship, object) values (?, ?, ?, ?, ?)";
2621
        try {
2622
            pStmt = connection.prepareStatement(sql);
2623
            //bind variable
2624
            pStmt.setString(1, docid);
2625
            pStmt.setString(2, doctype);
2626
            pStmt.setString(3, docid);
2627
            pStmt.setString(4, RELATION);
2628
            pStmt.setString(5, dataId);
2629
            //execute query
2630
            pStmt.execute();
2631
            pStmt.close();
2632
        }//try
2633
        catch (SQLException e) {
2634
            throw new SAXException(
2635
                    "EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
2636
                            + e.getMessage());
2637
        }//catch
2638
        finally {
2639
            try {
2640
                pStmt.close();
2641
            }//try
2642
            catch (SQLException ee) {
2643
                throw new SAXException(
2644
                        "EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
2645
                                + ee.getMessage());
2646
            }//catch
2647
        }//finally
2648

    
2649
    }//writeOnlineDataFileIdIntoRelationTable
2650

    
2651
    /*
2652
     * This method will handle data file in online url. If the data file is in
2653
     * ecogrid protocol, then the datafile identifier(without rev) be returned.
2654
     * otherwise, null will be returned.
2655
     * If the data file doesn't exsit in xml_documents or
2656
     * xml_revision table, or the user has all permission to the data file if
2657
     * the docid already existed, the data file id (without rev)will be returned
2658
     * NEED to do:
2659
     * We should also need to implement http and ftp. Those
2660
     * external files should be download and assign a data file id to it.
2661
     */
2662
    private String handleOnlineUrlDataFile(String url) throws SAXException
2663
    {
2664
      MetaCatUtil.debugMessage("The url is "+ url, 10);
2665
      String docid = null;
2666
      // if the url is not a ecogrid protocol, null will be getten
2667
      String accessionNumber =
2668
                 MetaCatUtil.getAccessionNumberFromEcogridIdentifier(url);
2669
      if (accessionNumber != null)
2670
      {
2671
        // handle ecogrid protocol
2672
        // get rid of revision number to get the docid.
2673
        docid = MetaCatUtil.getDocIdFromAccessionNumber(accessionNumber);
2674
        onlineDataFileIdInRelationVector.add(docid);
2675
        try
2676
        {
2677

    
2678
          if (!AccessionNumber.accNumberUsed(docid))
2679
          {
2680
            return docid;
2681
          }
2682
          PermissionController controller = new
2683
              PermissionController(accessionNumber);
2684
          if (controller.hasPermission(
2685
              user, groups, AccessControlInterface.ALLSTRING))
2686
          {
2687
            return docid;
2688
          }
2689
          else
2690
          {
2691
            throw new SAXException("User does not have permission to update " +
2692
                  "of access rules for data file "+ docid);
2693
          }
2694
        }//try
2695
        catch(Exception e)
2696
        {
2697
          MetaCatUtil.debugMessage("Eorr in " +
2698
                                "Eml200SAXHanlder.handleOnlineUrlDataFile is " +
2699
                                 e.getMessage(), 30);
2700
          throw new SAXException(e.getMessage());
2701
        }
2702
      }
2703
      return docid;
2704
    }
2705

    
2706
    private void compareElementNameSpaceAttributes(Stack unchangableNodeStack,
2707
            Hashtable nameSpaces, Attributes attributes, String localName,
2708
            String error) throws SAXException
2709
    {
2710
        //Get element subtree node stack (element node)
2711
        NodeRecord elementNode = null;
2712
        try {
2713
            elementNode = (NodeRecord) unchangableNodeStack.pop();
2714
        } catch (EmptyStackException ee) {
2715
            MetaCatUtil
2716
                    .debugMessage("Node stack is empty for element data", 35);
2717
            throw new SAXException(error);
2718
        }
2719
        MetaCatUtil.debugMessage("current node type from xml is ELEMENT", 40);
2720
        MetaCatUtil.debugMessage("node type from stack: "
2721
                + elementNode.getNodeType(), 40);
2722
        MetaCatUtil.debugMessage("node name from xml document: " + localName,
2723
                40);
2724
        MetaCatUtil.debugMessage("node name from stack: "
2725
                + elementNode.getNodeName(), 40);
2726
        MetaCatUtil.debugMessage("node data from stack: "
2727
                + elementNode.getNodeData(), 40);
2728
        MetaCatUtil.debugMessage("node id is: " + elementNode.getNodeId(), 40);
2729
        // if this node is not element or local name not equal or name space
2730
        // not
2731
        // equals, throw an exception
2732
        if (!elementNode.getNodeType().equals("ELEMENT")
2733
                || !localName.equals(elementNode.getNodeName()))
2734
        //  (uri != null && !uri.equals(elementNode.getNodePrefix())))
2735
        {
2736
            MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2737
            MetaCatUtil.debugMessage("current node type from xml is ELEMENT",
2738
                    40);
2739
            MetaCatUtil.debugMessage("node type from stack: "
2740
                    + elementNode.getNodeType(), 40);
2741
            MetaCatUtil.debugMessage("node name from xml document: "
2742
                    + localName, 40);
2743
            MetaCatUtil.debugMessage("node name from stack: "
2744
                    + elementNode.getNodeName(), 40);
2745
            MetaCatUtil.debugMessage("node data from stack: "
2746
                    + elementNode.getNodeData(), 40);
2747
            MetaCatUtil.debugMessage("node id is: " + elementNode.getNodeId(),
2748
                    40);
2749
            throw new SAXException(error);
2750
        }
2751

    
2752
        //compare namespace
2753
        Enumeration nameEn = nameSpaces.keys();
2754
        while (nameEn.hasMoreElements()) {
2755
            //Get namespacke node stack (element node)
2756
            NodeRecord nameNode = null;
2757
            try {
2758
                nameNode = (NodeRecord) unchangableNodeStack.pop();
2759
            } catch (EmptyStackException ee) {
2760
                MetaCatUtil.debugMessage(
2761
                        "Node stack is empty for namespace data", 35);
2762
                throw new SAXException(error);
2763
            }
2764

    
2765
            String prefixName = (String) nameEn.nextElement();
2766
            String nameSpaceUri = (String) nameSpaces.get(prefixName);
2767
            if (!nameNode.getNodeType().equals("NAMESPACE")
2768
                    || !prefixName.equals(nameNode.getNodeName())
2769
                    || !nameSpaceUri.equals(nameNode.getNodeData())) {
2770
                MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2771
                MetaCatUtil.debugMessage(
2772
                        "current node type from xml is NAMESPACE", 40);
2773
                MetaCatUtil.debugMessage("node type from stack: "
2774
                        + nameNode.getNodeType(), 40);
2775
                MetaCatUtil.debugMessage("current node name from xml is: "
2776
                        + prefixName, 40);
2777
                MetaCatUtil.debugMessage("node name from stack: "
2778
                        + nameNode.getNodeName(), 40);
2779
                MetaCatUtil.debugMessage("current node data from xml is: "
2780
                        + nameSpaceUri, 40);
2781
                MetaCatUtil.debugMessage("node data from stack: "
2782
                        + nameNode.getNodeData(), 40);
2783
                MetaCatUtil.debugMessage("node id is: " + nameNode.getNodeId(),
2784
                        40);
2785
                throw new SAXException(error);
2786
            }
2787

    
2788
        }//while
2789

    
2790
        //compare attributes
2791
        for (int i = 0; i < attributes.getLength(); i++) {
2792
            NodeRecord attriNode = null;
2793
            try {
2794
                attriNode = (NodeRecord) unchangableNodeStack.pop();
2795

    
2796
            } catch (EmptyStackException ee) {
2797
                MetaCatUtil.debugMessage(
2798
                        "Node stack is empty for attribute data", 35);
2799
                throw new SAXException(error);
2800
            }
2801
            String attributeName = attributes.getQName(i);
2802
            String attributeValue = attributes.getValue(i);
2803
            MetaCatUtil.debugMessage(
2804
                    "current node type from xml is ATTRIBUTE ", 40);
2805
            MetaCatUtil.debugMessage("node type from stack: "
2806
                    + attriNode.getNodeType(), 40);
2807
            MetaCatUtil.debugMessage("current node name from xml is: "
2808
                    + attributeName, 40);
2809
            MetaCatUtil.debugMessage("node name from stack: "
2810
                    + attriNode.getNodeName(), 40);
2811
            MetaCatUtil.debugMessage("current node data from xml is: "
2812
                    + attributeValue, 40);
2813
            MetaCatUtil.debugMessage("node data from stack: "
2814
                    + attriNode.getNodeData(), 40);
2815
            MetaCatUtil.debugMessage("node id  is: " + attriNode.getNodeId(),
2816
                    40);
2817

    
2818
            if (!attriNode.getNodeType().equals("ATTRIBUTE")
2819
                    || !attributeName.equals(attriNode.getNodeName())
2820
                    || !attributeValue.equals(attriNode.getNodeData())) {
2821
                MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2822
                MetaCatUtil.debugMessage(
2823
                        "current node type from xml is ATTRIBUTE ", 40);
2824
                MetaCatUtil.debugMessage("node type from stack: "
2825
                        + attriNode.getNodeType(), 40);
2826
                MetaCatUtil.debugMessage("current node name from xml is: "
2827
                        + attributeName, 40);
2828
                MetaCatUtil.debugMessage("node name from stack: "
2829
                        + attriNode.getNodeName(), 40);
2830
                MetaCatUtil.debugMessage("current node data from xml is: "
2831
                        + attributeValue, 40);
2832
                MetaCatUtil.debugMessage("node data from stack: "
2833
                        + attriNode.getNodeData(), 40);
2834
                MetaCatUtil.debugMessage("node is: " + attriNode.getNodeId(),
2835
                        40);
2836
                throw new SAXException(error);
2837
            }
2838
        }//for
2839

    
2840
    }
2841

    
2842
    /* mehtod to compare current text node and node in db */
2843
    private void compareTextNode(Stack nodeStack, StringBuffer text,
2844
            String error) throws SAXException
2845
    {
2846
        NodeRecord node = null;
2847
        //get node from current stack
2848
        try {
2849
            node = (NodeRecord) nodeStack.pop();
2850
        } catch (EmptyStackException ee) {
2851
            MetaCatUtil.debugMessage(
2852
                    "Node stack is empty for text data in startElement", 35);
2853
            throw new SAXException(error);
2854
        }
2855
        MetaCatUtil.debugMessage(
2856
                "current node type from xml is TEXT in start element", 40);
2857
        MetaCatUtil.debugMessage("node type from stack: " + node.getNodeType(),
2858
                40);
2859
        MetaCatUtil.debugMessage("current node data from xml is: "
2860
                + text.toString(), 40);
2861
        MetaCatUtil.debugMessage("node data from stack: " + node.getNodeData(),
2862
                40);
2863
        MetaCatUtil.debugMessage("node name from stack: " + node.getNodeName(),
2864
                40);
2865
        MetaCatUtil.debugMessage("node is: " + node.getNodeId(), 40);
2866
        if (!node.getNodeType().equals("TEXT")
2867
                || !(text.toString()).equals(node.getNodeData())) {
2868
            MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2869
            MetaCatUtil.debugMessage(
2870
                    "current node type from xml is TEXT in start element", 40);
2871
            MetaCatUtil.debugMessage("node type from stack: "
2872
                    + node.getNodeType(), 40);
2873
            MetaCatUtil.debugMessage("current node data from xml is: "
2874
                    + text.toString(), 40);
2875
            MetaCatUtil.debugMessage("node data from stack: "
2876
                    + node.getNodeData(), 40);
2877
            MetaCatUtil.debugMessage("node name from stack: "
2878
                    + node.getNodeName(), 40);
2879
            MetaCatUtil.debugMessage("node is: " + node.getNodeId(), 40);
2880
            throw new SAXException(error);
2881
        }//if
2882
    }
2883

    
2884
    /* Comparet comment from xml and db */
2885
    private void compareCommentNode(Stack nodeStack, String string, String error)
2886
            throws SAXException
2887
    {
2888
        NodeRecord node = null;
2889
        try {
2890
            node = (NodeRecord) nodeStack.pop();
2891
        } catch (EmptyStackException ee) {
2892
            MetaCatUtil.debugMessage("the stack is empty for comment data", 32);
2893
            throw new SAXException(error);
2894
        }
2895
        MetaCatUtil.debugMessage("current node type from xml is COMMENT", 40);
2896
        MetaCatUtil.debugMessage("node type from stack: " + node.getNodeType(),
2897
                40);
2898
        MetaCatUtil
2899
                .debugMessage("current node data from xml is: " + string, 40);
2900
        MetaCatUtil.debugMessage("node data from stack: " + node.getNodeData(),
2901
                40);
2902
        MetaCatUtil.debugMessage("node is from stack: " + node.getNodeId(), 40);
2903
        // if not consistent terminate program and throw a exception
2904
        if (!node.getNodeType().equals("COMMENT")
2905
                || !string.equals(node.getNodeData())) {
2906
            MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2907
            MetaCatUtil.debugMessage("current node type from xml is COMMENT",
2908
                    40);
2909
            MetaCatUtil.debugMessage("node type from stack: "
2910
                    + node.getNodeType(), 40);
2911
            MetaCatUtil.debugMessage(
2912
                    "current node data from xml is: " + string, 40);
2913
            MetaCatUtil.debugMessage("node data from stack: "
2914
                    + node.getNodeData(), 40);
2915
            MetaCatUtil.debugMessage("node is from stack: " + node.getNodeId(),
2916
                    40);
2917
            throw new SAXException(error);
2918
        }//if
2919
    }
2920

    
2921
    /* Compare whitespace from xml and db */
2922
   private void compareWhiteSpace(Stack nodeStack, String string, String error)
2923
           throws SAXException
2924
   {
2925
       NodeRecord node = null;
2926
       try {
2927
           node = (NodeRecord) nodeStack.pop();
2928
       } catch (EmptyStackException ee) {
2929
           MetaCatUtil.debugMessage("the stack is empty for whitespace data",
2930
                   32);
2931
           throw new SAXException(error);
2932
       }
2933
       if (!node.getNodeType().equals("TEXT")
2934
               || !string.equals(node.getNodeData())) {
2935
           MetaCatUtil.debugMessage("Inconsistence happend: ", 40);
2936
           MetaCatUtil.debugMessage(
2937
                   "current node type from xml is WHITESPACE TEXT", 40);
2938
           MetaCatUtil.debugMessage("node type from stack: "
2939
                   + node.getNodeType(), 40);
2940
           MetaCatUtil.debugMessage(
2941
                   "current node data from xml is: " + string, 40);
2942
           MetaCatUtil.debugMessage("node data from stack: "
2943
                   + node.getNodeData(), 40);
2944
           MetaCatUtil.debugMessage("node is from stack: " + node.getNodeId(),
2945
                   40);
2946
           throw new SAXException(error);
2947
       }//if
2948
   }
2949

    
2950

    
2951

    
2952
}
(34-34/63)