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
 *
9
 *   '$Author: daigle $'
10
 *     '$Date: 2008-07-06 21:25:34 -0700 (Sun, 06 Jul 2008) $'
11
 * '$Revision: 4080 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.BufferedReader;
31
import java.io.BufferedWriter;
32
import java.io.File;
33
import java.io.FileReader;
34
import java.io.FileWriter;
35
import java.io.IOException;
36
import java.io.Reader;
37
import java.sql.PreparedStatement;
38
import java.sql.ResultSet;
39
import java.sql.SQLException;
40
import java.sql.Statement;
41
import java.util.EmptyStackException;
42
import java.util.Enumeration;
43
import java.util.Hashtable;
44
import java.util.Stack;
45
import java.util.Vector;
46

    
47
import org.apache.log4j.Logger;
48
import org.xml.sax.Attributes;
49
import org.xml.sax.SAXException;
50

    
51
import edu.ucsb.nceas.metacat.service.PropertyService;
52
import edu.ucsb.nceas.metacat.util.LDAPUtil;
53
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
54
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
55

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

    
116
    // now additionalAccess will be explained as distribution access control
117
    // - data file
118
    private boolean processAdditionalAccess = false;
119

    
120
    private boolean processOtherAccess = false;
121

    
122
    private AccessSection accessObject = null;
123

    
124
    private AccessRule accessRule = null;
125

    
126
    private Vector describesId = new Vector(); // store the ids in
127
                                               //additionalmetadata/describes
128

    
129
    //store all distribution element id for online url. key is the distribution
130
    // id and  data  is url
131
    private Hashtable onlineURLDistributionIdList = new Hashtable();
132
    // distribution/oneline/url will store this vector if distribution doesn't
133
    // have a id.
134
    private Vector onelineURLDistributionListWithoutId = new Vector();
135

    
136
    //store all distribution element id for online other distribution, such as
137
    // connection or connectiondefination. key is the distribution id
138
    // and  data  is distribution id
139
    private Hashtable onlineOtherDistributionIdList = new Hashtable();
140

    
141
    //store all distribution element id for inline data.
142
    // key is the distribution id, data is the internal inline id
143
    private Hashtable inlineDistributionIdList = new Hashtable();
144

    
145
    //store all distribution element id for off line data.
146
    // key is the distribution id, data is the id too.
147
    private Hashtable offlineDistributionIdList = new Hashtable();
148

    
149
    // a hash to stored all distribution id, both key and value are id itself
150
    private Hashtable distributionAllIdList = new Hashtable();
151

    
152
    // temporarily store distribution id
153
    private String distributionId = null;
154

    
155
    // flag to indicate to handle distrubiton
156
    private boolean proccessDistribution = false;
157

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

    
169
    private boolean needCheckingAccessModule = false;
170

    
171
    private AccessSection unChangebleTopAccessSubTree = null;
172

    
173
    private Vector unChangebleAdditionalAccessSubTreeVector = new Vector();
174

    
175
    private Hashtable unChangebleReferencedAccessSubTreeHash = new Hashtable();
176

    
177
    private AccessSection topAccessSection;
178

    
179
    private Vector addtionalAccessVector = new Vector();
180

    
181
    // key is subtree id and value is accessSection object
182
    private Hashtable possibleReferencedAccessHash = new Hashtable();
183

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

    
188
    // vector stored the data file id which will be write into relation table
189
    private Vector onlineDataFileIdInRelationVector = new Vector();
190

    
191
    // Indicator of inline data
192
    private boolean handleInlineData = false;
193

    
194
    private Hashtable inlineDataNameSpace = null;
195

    
196
    private FileWriter inlineDataFileWriter = null;
197

    
198
    private String inlineDataFileName = null;
199

    
200
    private int inLineDataIndex = 0;
201

    
202
    private Vector inlineFileIDList = new Vector();
203

    
204
    private boolean inAddtionalMetaData = false;
205

    
206
    //user has unwritable inline data object when it updates a document
207
    private boolean unWritableInlineDataObject = false;
208
    //user has unreadable inline data when it updates a dcoument
209
    private boolean unReadableInlineDataObject = false;
210

    
211
    // the hashtable contains the info from xml_access table which
212
    // inline data the user can't read when user update a document.
213
    // The key in hashtable is subtree id and data is the inline data internal
214
    // file name.
215

    
216
    private Hashtable previousUnreadableInlineDataObjectHash = new Hashtable();
217

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

    
224
    private Hashtable accessSubTreeAlreadyWriteDBList = new Hashtable();
225

    
226
    //This hashtable will stored the id which already has additional access
227
    // control. So the top level access control will ignore them.
228
    private Hashtable onlineURLIdHasAddtionalAccess   = new Hashtable();
229

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

    
244
    private int numberOfHitUnWritableInlineData = 0;
245

    
246
    // Constant
247
    private static final String EML = "eml";
248

    
249
    private static final String DESCRIBES = "describes";
250

    
251
    private static final String ADDITIONALMETADATA = "additionalMetadata";
252

    
253
    private static final String ORDER = "order";
254

    
255
    private static final String ID = "id";
256

    
257
    private static final String REFERENCES = "references";
258

    
259
    public static final String INLINE = "inline";
260

    
261
    private static final String ONLINE = "online";
262

    
263
    private static final String OFFLINE = "offline";
264

    
265
    private static final String CONNECTION = "connection";
266

    
267
    private static final String CONNECTIONDEFINITION = "connectionDefinition";
268

    
269
    private static final String URL = "url";
270

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

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

    
277
    public static final String TOPLEVEL = "top";
278

    
279
    public static final String DATAACCESSLEVEL = "dataAccess";
280

    
281
    // this level is for the access module which is not in top or additional
282
    // place, but it was referenced by top or additional
283
    private static final String REFERENCEDLEVEL = "referenced";
284

    
285
    private static final String RELATION = "Provides info for";
286

    
287
    private static final String DISTRIBUTION = "distribution";
288

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

    
320
            //If the action is update and user doesn't have "ALL" permission
321
            // we need to check if user update access subtree
322
            if (action != null && action.equals("UPDATE")
323
                    && !control.hasPermission(user, groups,
324
                            AccessControlInterface.ALLSTRING) 
325
                            && !LDAPUtil.isAdministrator(user, groups))
326
            {
327
                needCheckingAccessModule = true;
328
                unChangebleTopAccessSubTree = getTopAccessSubTreeFromDB();
329
                unChangebleAdditionalAccessSubTreeVector =
330
                                         getAdditionalAccessSubTreeListFromDB();
331
                unChangebleReferencedAccessSubTreeHash =
332
                                         getReferencedAccessSubTreeListFromDB();
333
            }
334

    
335
            //Here is for  data object checking.
336
            if (action != null && action.equals("UPDATE"))
337
            {
338
              //info about inline data object which user doesn't have read
339
              //permission the info come from xml_access table
340
              previousUnreadableInlineDataObjectHash = PermissionController.
341
                            getUnReadableInlineDataIdList(docid, user,
342
                                                          groups, true);
343

    
344
              //info about data object which user doesn't have write permission
345
              // the info come from xml_accesss table
346
              previousUnwritableInlineDataObjectHash = PermissionController.
347
                            getUnWritableInlineDataIdList(docid, user,
348
                                                          groups, true);
349

    
350
            }
351

    
352

    
353
        }
354
        catch (Exception e)
355
        {
356
            logMetacat.error("erorr in Eml200SAXHanlder is "
357
                                     +e.getMessage());
358
            throw new SAXException(e.getMessage());
359
        }
360
    }
361

    
362
    /*
363
     * Get the top level access subtree info from xml_accesssubtree table.
364
     * If no top access subtree found, null will be return.
365
     */
366
     private AccessSection getTopAccessSubTreeFromDB()
367
                                                       throws SAXException
368
     {
369
       AccessSection topAccess = null;
370
       PreparedStatement pstmt = null;
371
       ResultSet rs = null;
372
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
373
                + "FROM xml_accesssubtree WHERE docid like ? "
374
                + "AND controllevel like ?";
375

    
376

    
377
       try
378
       {
379
            pstmt = connection.prepareStatement(sql);
380
            // Increase DBConnection usage count
381
            connection.increaseUsageCount(1);
382
            // Bind the values to the query
383
            pstmt.setString(1, docid);
384
            pstmt.setString(2, TOPLEVEL);
385
            pstmt.execute();
386

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

    
425
     }
426

    
427
    /*
428
     * Get the subtree node info from xml_accesssubtree table
429
     */
430
    private Vector getAdditionalAccessSubTreeListFromDB() throws Exception
431
    {
432
        Vector result = new Vector();
433
        PreparedStatement pstmt = null;
434
        ResultSet rs = null;
435
        String sql = "SELECT subtreeid, startnodeid, endnodeid "
436
                + "FROM xml_accesssubtree WHERE docid like ? "
437
                + "AND controllevel like ? "
438
                + "ORDER BY startnodeid ASC";
439

    
440
        try
441
        {
442

    
443
            pstmt = connection.prepareStatement(sql);
444
            // Increase DBConnection usage count
445
            connection.increaseUsageCount(1);
446
            // Bind the values to the query
447
            pstmt.setString(1, docid);
448
            pstmt.setString(2, DATAACCESSLEVEL);
449
            pstmt.execute();
450

    
451
            // Get result set
452
            rs = pstmt.getResultSet();
453
            while (rs.next())
454
            {
455
                String sectionId = rs.getString(1);
456
                long startNodeId = rs.getLong(2);
457
                long endNodeId = rs.getLong(3);
458
                // create a new access section
459
                AccessSection accessObj = new AccessSection();
460
                accessObj.setControlLevel(DATAACCESSLEVEL);
461
                accessObj.setDocId(docid);
462
                accessObj.setSubTreeId(sectionId);
463
                accessObj.setStartNodeId(startNodeId);
464
                accessObj.setEndNodeId(endNodeId);
465
                // add this access obj into vector
466
                result.add(accessObj);
467

    
468
            }
469
            pstmt.close();
470
        }//try
471
        catch (SQLException e)
472
        {
473
            throw new SAXException(
474
                    "EMLSAXHandler.getAddtionalAccessSubTreeListFromDB(): "
475
                            + e.getMessage());
476
        }//catch
477
        finally
478
        {
479
            try
480
            {
481
                pstmt.close();
482
            }
483
            catch (SQLException ee)
484
            {
485
                throw new SAXException(
486
                        "EMLSAXHandler.getAccessSubTreeListFromDB(): "
487
                                + ee.getMessage());
488
            }
489
        }//finally
490
        return result;
491
    }
492

    
493
   /*
494
    * Get the access subtree for referenced info from xml_accesssubtree table
495
    */
496
   private Hashtable getReferencedAccessSubTreeListFromDB() throws Exception
497
   {
498
       Hashtable result = new Hashtable();
499
       PreparedStatement pstmt = null;
500
       ResultSet rs = null;
501
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
502
               + "FROM xml_accesssubtree WHERE docid like ? "
503
               + "AND controllevel like ? "
504
               + "ORDER BY startnodeid ASC";
505

    
506
       try
507
       {
508

    
509
           pstmt = connection.prepareStatement(sql);
510
           // Increase DBConnection usage count
511
           connection.increaseUsageCount(1);
512
           // Bind the values to the query
513
           pstmt.setString(1, docid);
514
           pstmt.setString(2, REFERENCEDLEVEL);
515
           pstmt.execute();
516

    
517
           // Get result set
518
           rs = pstmt.getResultSet();
519
           while (rs.next())
520
           {
521
               String sectionId = rs.getString(1);
522
               long startNodeId = rs.getLong(2);
523
               long endNodeId = rs.getLong(3);
524
               // create a new access section
525
               AccessSection accessObj = new AccessSection();
526
               accessObj.setControlLevel(DATAACCESSLEVEL);
527
               accessObj.setDocId(docid);
528
               accessObj.setSubTreeId(sectionId);
529
               accessObj.setStartNodeId(startNodeId);
530
               accessObj.setEndNodeId(endNodeId);
531
               // add this access obj into hastable
532
               if ( sectionId != null && !sectionId.trim().equals(""))
533
               {
534
                 result.put(sectionId, accessObj);
535
               }
536

    
537
           }
538
           pstmt.close();
539
       }//try
540
       catch (SQLException e)
541
       {
542
           throw new SAXException(
543
                   "EMLSAXHandler.getReferencedAccessSubTreeListFromDB(): "
544
                           + e.getMessage());
545
       }//catch
546
       finally
547
       {
548
           try
549
           {
550
               pstmt.close();
551
           }
552
           catch (SQLException ee)
553
           {
554
               throw new SAXException(
555
                       "EMLSAXHandler.getReferencedSubTreeListFromDB(): "
556
                               + ee.getMessage());
557
           }
558
       }//finally
559
       return result;
560
   }
561

    
562

    
563

    
564
    /** SAX Handler that is called at the start of each XML element */
565
    public void startElement(String uri, String localName, String qName,
566
            Attributes atts) throws SAXException
567
    {
568
        // for element <eml:eml...> qname is "eml:eml", local name is "eml"
569
        // for element <acl....> both qname and local name is "eml"
570
        // uri is namesapce
571
        logMetacat.info("Start ELEMENT(qName) " + qName);
572
        logMetacat.info("Start ELEMENT(localName) " + localName);
573
        logMetacat.info("Start ELEMENT(uri) " + uri);
574

    
575
        DBSAXNode parentNode = null;
576
        DBSAXNode currentNode = null;
577
        // none inline part
578
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
579
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
580
        if (!handleInlineData)
581
        {
582
            // Get a reference to the parent node for the id
583
            try
584
            {
585
                parentNode = (DBSAXNode) nodeStack.peek();
586
            }
587
            catch (EmptyStackException e)
588
            {
589
                parentNode = null;
590
            }
591

    
592
            //start handle inline data
593
            //=====================================================
594
            if (qName.equals(INLINE) && !inAddtionalMetaData)
595
            {
596
                handleInlineData = true;
597
                inLineDataIndex++;
598
                //intitialize namespace hash for in line data
599
                inlineDataNameSpace = new Hashtable();
600
                //initialize file writer
601
                String docidWithoutRev = MetaCatUtil.getDocIdFromString(docid);
602
                String seperator = ".";
603
                try {
604
					seperator = PropertyService.getProperty("accNumSeparator");
605
				} catch (PropertyNotFoundException pnfe) {
606
					logMetacat.error("Could not get property 'accNumSeparator'.  " 
607
							+ "Setting separator to '.': "+ pnfe.getMessage());
608
				}
609
                // the new file name will look like docid.rev.2
610
                inlineDataFileName = docidWithoutRev + seperator + revision
611
                        + seperator + inLineDataIndex;
612
                inlineDataFileWriter = createInlineDataFileWriter(inlineDataFileName);
613
                // put the inline file id into a vector. If upload failed,
614
                // metacat will
615
                // delete the inline data file
616
                inlineFileIDList.add(inlineDataFileName);
617

    
618
                // put distribution id and inline file id into a  hash
619
                if (distributionId != null)
620
                {
621
                  //check to see if this inline data is readable or writable to
622
                  // this user
623
                  if (!previousUnreadableInlineDataObjectHash.isEmpty() &&
624
                       previousUnreadableInlineDataObjectHash.containsKey(distributionId))
625
                  {
626
                      unReadableInlineDataObject = true;
627
                  }
628
                  if (!previousUnwritableInlineDataObjectHash.isEmpty() &&
629
                       previousUnwritableInlineDataObjectHash.containsKey(distributionId))
630
                  {
631
                     unWritableInlineDataObject = true;
632
                     numberOfHitUnWritableInlineData++;
633
                  }
634

    
635

    
636
                  // store the distributid and inlinedata filename into a hash
637
                  inlineDistributionIdList.put(distributionId, inlineDataFileName);
638
                }
639

    
640
            }
641
            //==============================================================
642

    
643

    
644
            // If hit a text node, we need write this text for current's parent
645
            // node
646
            // This will happend if the element is mixted
647
            //==============================================================
648
            if (hitTextNode && parentNode != null)
649
            {
650

    
651

    
652
                if (needCheckingAccessModule
653
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
654
                    // stored the pull out nodes into storedNode stack
655
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
656
                            null, null, MetaCatUtil.normalize(textBuffer
657
                                    .toString()));
658
                    storedAccessNodeStack.push(nodeElement);
659

    
660
                }
661

    
662
                // write the textbuffer into db for parent node.
663
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
664
                        parentNode);
665
                // rest hitTextNode
666
                hitTextNode = false;
667
                // reset textbuffer
668
                textBuffer = null;
669
                textBuffer = new StringBuffer();
670

    
671
            }
672
            //==================================================================
673

    
674
            // Document representation that points to the root document node
675
            //==================================================================
676
            if (atFirstElement)
677
            {
678
                atFirstElement = false;
679
                // If no DOCTYPE declaration: docname = root element
680
                // doctype = root element name or name space
681
                if (docname == null) {
682
                    docname = localName;
683
                    // if uri isn't null doctype = uri(namespace)
684
                    // othewise root element
685
                    if (uri != null && !(uri.trim()).equals("")) {
686
                        doctype = uri;
687
                    } else {
688
                        doctype = docname;
689
                    }
690
                    logMetacat.info("DOCNAME-a: " + docname);
691
                    logMetacat.info("DOCTYPE-a: " + doctype);
692
                } else if (doctype == null) {
693
                    // because docname is not null and it is declared in dtd
694
                    // so could not be in schema, no namespace
695
                    doctype = docname;
696
                    logMetacat.info("DOCTYPE-b: " + doctype);
697
                }
698
                rootNode.writeNodename(docname);
699
                //System.out.println("here!!!!!!!!!!!!!!!!!!1");
700
                try {
701
                    // for validated XML Documents store a reference to XML DB
702
                    // Catalog
703
                    // Because this is select statement and it needn't to roll
704
                    // back if
705
                    // insert document action fialed.
706
                    // In order to decrease DBConnection usage count, we get a
707
                    // new
708
                    // dbconnection from pool
709
                    //String catalogid = null;
710
                    DBConnection dbConn = null;
711
                    int serialNumber = -1;
712

    
713
                    try {
714
                        // Get dbconnection
715
                        dbConn = DBConnectionPool
716
                                .getDBConnection("DBSAXHandler.startElement");
717
                        serialNumber = dbConn.getCheckOutSerialNumber();
718

    
719
                        Statement stmt = dbConn.createStatement();
720
                        ResultSet rs = stmt
721
                                .executeQuery("SELECT catalog_id FROM xml_catalog "
722
                                        + "WHERE entry_type = 'Schema' "
723
                                        + "AND public_id = '" + doctype + "'");
724
                        boolean hasRow = rs.next();
725
                        if (hasRow) {
726
                            catalogid = rs.getString(1);
727
                        }
728
                        stmt.close();
729
                        //System.out.println("here!!!!!!!!!!!!!!!!!!2");
730
                    }//try
731
                    finally {
732
                        // Return dbconnection
733
                        DBConnectionPool.returnDBConnection(dbConn,
734
                                serialNumber);
735
                    }//finally
736

    
737
                    //create documentImpl object by the constructor which can
738
                    // specify
739
                    //the revision
740
                    if (!super.getIsRevisionDoc())
741
                    {
742
                       
743
                       currentDocument = new DocumentImpl(connection, rootNode
744
                            .getNodeID(), docname, doctype, docid, revision,
745
                            action, user, this.pub, catalogid, this.serverCode, 
746
                            createDate, updateDate);
747
                    }
748
                   
749

    
750
                } catch (Exception ane) {
751
                    throw (new SAXException(
752
                            "Error in EMLSaxHandler.startElement " + action,
753
                            ane));
754
                }
755
                
756
            }
757
            //==================================================================
758

    
759
            // node
760
            //==================================================================
761
            // Create the current node representation
762
            currentNode = new DBSAXNode(connection, qName, localName,
763
                    parentNode, rootNode.getNodeID(), docid,
764
                    doctype);
765
            // Use a local variable to store the element node id
766
            // If this element is a start point of subtree(section), it will be
767
            // stored
768
            // otherwise, it will be discated
769
            long startNodeId = currentNode.getNodeID();
770
            // Add all of the namespaces
771
            String prefix = null;
772
            String nsuri = null;
773
            Enumeration prefixes = namespaces.keys();
774
            while (prefixes.hasMoreElements())
775
            {
776
                prefix = (String) prefixes.nextElement();
777
                nsuri = (String) namespaces.get(prefix);
778
                endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
779
            }
780

    
781
            //=================================================================
782
           // attributes
783
           // Add all of the attributes
784
          for (int i = 0; i < atts.getLength(); i++)
785
          {
786
              String attributeName = atts.getQName(i);
787
              String attributeValue = atts.getValue(i);
788
              endNodeId = currentNode.setAttribute(attributeName,
789
                      attributeValue, docid);
790

    
791
              // To handle name space and schema location if the attribute
792
              // name is
793
              // xsi:schemaLocation. If the name space is in not in catalog
794
              // table
795
              // it will be regeistered.
796
              if (attributeName != null
797
                      && attributeName
798
                              .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
799
                  SchemaLocationResolver resolver = new SchemaLocationResolver(
800
                          attributeValue);
801
                  resolver.resolveNameSpace();
802

    
803
              }
804
              else if (attributeName != null && attributeName.equals(ID) &&
805
                       currentNode.getTagName().equals(DISTRIBUTION) &&
806
                       !inAddtionalMetaData)
807
              {
808
                 // this is a distribution element and the id is distributionID
809
                 distributionId = attributeValue;
810
                 distributionAllIdList.put(distributionId, distributionId);
811

    
812
              }
813

    
814
          }//for
815

    
816

    
817
           //=================================================================
818

    
819
            // handle access stuff
820
            //==================================================================
821
            if (localName.equals(ACCESS))
822
            {
823
                //make sure the access is top level
824
                // this mean current node's parent's parent should be "eml"
825
                DBSAXNode tmpNode = (DBSAXNode) nodeStack.pop();// pop out
826
                                                                    // parent
827
                                                                    // node
828
                //peek out grandParentNode
829
                DBSAXNode grandParentNode = (DBSAXNode) nodeStack.peek();
830
                // put parent node back
831
                nodeStack.push(tmpNode);
832
                String grandParentTag = grandParentNode.getTagName();
833
                if (grandParentTag.equals(EML) && !inAddtionalMetaData)
834
                {
835
                  processTopLeverAccess = true;
836

    
837
                }
838
                else if ( !inAddtionalMetaData )
839
                {
840
                  // process other access embedded into resource level
841
                  // module
842
                  processOtherAccess = true;
843
                }
844
                else
845
                {
846
                  // this for access in additional data which don't have
847
                  // described element. If it has a descirbed element,
848
                  // this code would hurt any thing
849
                  processAdditionalAccess = true;
850
                  logMetacat.warn("accessing process addtional access true when meet access");
851
                }
852

    
853

    
854
                // create access object
855
                accessObject = new AccessSection();
856
                // set permission order
857
                String permOrder = currentNode.getAttribute(ORDER);
858
                accessObject.setPermissionOrder(permOrder);
859
                // set access id
860
                String accessId = currentNode.getAttribute(ID);
861
                accessObject.setSubTreeId(accessId);
862
                // for additional access subtree, the  start of node id should
863
                // be describe element. We also stored the start access element
864
                // node id too.
865
                if (processAdditionalAccess)
866
                {
867
                  accessObject.seStartedDescribesNodeId(firstDescribesNodeId);
868
                  accessObject.setControlLevel(DATAACCESSLEVEL);
869
                }
870
                else if (processTopLeverAccess)
871
                {
872
                  accessObject.setControlLevel(TOPLEVEL);
873
                }
874
                else if (processOtherAccess)
875
                {
876
                  accessObject.setControlLevel(REFERENCEDLEVEL);
877
                }
878

    
879
                accessObject.setStartNodeId(startNodeId);
880
                accessObject.setDocId(docid);
881

    
882

    
883

    
884
            }
885
            // Set up a access rule for allow
886
            else if (parentNode.getTagName() != null
887
                    && (parentNode.getTagName()).equals(ACCESS)
888
                    && localName.equals(ALLOW))
889
           {
890

    
891
                accessRule = new AccessRule();
892

    
893
                //set permission type "allow"
894
                accessRule.setPermissionType(ALLOW);
895

    
896
            }
897
            // set up an access rule for den
898
            else if (parentNode.getTagName() != null
899
                    && (parentNode.getTagName()).equals(ACCESS)
900
                    && localName.equals(DENY))
901
           {
902
                accessRule = new AccessRule();
903
                //set permission type "allow"
904
                accessRule.setPermissionType(DENY);
905
            }
906

    
907
            //=================================================================
908
            // some other independ stuff
909

    
910
            // Add the node to the stack, so that any text data can be
911
            // added as it is encountered
912
            nodeStack.push(currentNode);
913
            // Add the node to the vector used by thread for writing XML Index
914
            nodeIndex.addElement(currentNode);
915

    
916
            // store access module element and attributes into stored stack
917
            if (needCheckingAccessModule
918
                    && (processAdditionalAccess || processOtherAccess || processTopLeverAccess))
919
            {
920
                // stored the pull out nodes into storedNode stack
921
                NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
922
                        localName, prefix, MetaCatUtil.normalize(null));
923
                storedAccessNodeStack.push(nodeElement);
924
                for (int i = 0; i < atts.getLength(); i++) {
925
                    String attributeName = atts.getQName(i);
926
                    String attributeValue = atts.getValue(i);
927
                    NodeRecord nodeAttribute = new NodeRecord(-2, -2, -2,
928
                            "ATTRIBUTE", attributeName, null, MetaCatUtil
929
                                    .normalize(attributeValue));
930
                    storedAccessNodeStack.push(nodeAttribute);
931
                }
932

    
933
            }
934

    
935
            if (currentNode.getTagName().equals(ADDITIONALMETADATA))
936
            {
937
              inAddtionalMetaData = true;
938
            }
939
            else if (currentNode.getTagName().equals(DESCRIBES) &&
940
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
941
                     firstDescribesInAdditionalMetadata)
942
            {
943
              // this is first decirbes element in additional metadata
944
              firstDescribesNodeId = startNodeId;
945
              // we started process additional access rules here
946
              // because access and describe couldn't be seperated
947
              NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
948
                        localName, prefix, MetaCatUtil.normalize(null));
949
              storedAccessNodeStack.push(nodeElement);
950
              processAdditionalAccess = true;
951
              logMetacat.warn("set processAdditonalAccess ture when meet describe");
952
            }
953
            else if (inAddtionalMetaData && processAdditionalAccess &&
954
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
955
                     !currentNode.getTagName().equals(DESCRIBES) &&
956
                     !currentNode.getTagName().equals(ACCESS))
957
            {
958
               // we start processAddtionalAccess  module when first hit describes
959
               // in additionalMetadata. So this is possible, there are
960
               // "describes" but not "access". So here is try to terminate
961
               // processAddionalAccess. In this situation, there another element
962
               // rather than "describes" or "access" as a child of additionalMetadata
963
               // so this is impossible it will have access element now.
964
               // If additionalMetadata has access element, the flag will be
965
               // terminated in endElement
966
               processAdditionalAccess = false;
967
               logMetacat.warn("set processAddtionAccess false if the there is no access in additional");
968
            }
969
            else if (currentNode.getTagName().equals(DISTRIBUTION) &&
970
                     !inAddtionalMetaData)
971
            {
972
              proccessDistribution = true;
973
            }
974

    
975

    
976
             //==================================================================
977
            // reset name space
978
            namespaces = null;
979
            namespaces = new Hashtable();
980

    
981
        }//not inline data
982
        // inline data
983
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
984
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
985
        else
986
        {
987
            // we don't buffer the inline data in characters() method
988
            // so start character don't need to hand text node.
989

    
990
            // inline data may be the xml format.
991
            StringBuffer inlineElements = new StringBuffer();
992
            inlineElements.append("<").append(qName);
993
            // append attributes
994
            for (int i = 0; i < atts.getLength(); i++) {
995
                String attributeName = atts.getQName(i);
996
                String attributeValue = atts.getValue(i);
997
                inlineElements.append(" ");
998
                inlineElements.append(attributeName);
999
                inlineElements.append("=\"");
1000
                inlineElements.append(attributeValue);
1001
                inlineElements.append("\"");
1002
            }
1003
            // append namespace
1004
            String prefix = null;
1005
            String nsuri = null;
1006
            Enumeration prefixes = inlineDataNameSpace.keys();
1007
            while (prefixes.hasMoreElements()) {
1008
                prefix = (String) prefixes.nextElement();
1009
                nsuri =  (String)  inlineDataNameSpace.get(prefix);
1010
                inlineElements.append(" ");
1011
                inlineElements.append("xmlns:");
1012
                inlineElements.append(prefix);
1013
                inlineElements.append("=\"");
1014
                inlineElements.append(nsuri);
1015
                inlineElements.append("\"");
1016
            }
1017
            inlineElements.append(">");
1018
            //reset inline data name space
1019
            inlineDataNameSpace = null;
1020
            inlineDataNameSpace = new Hashtable();
1021
            //write inline data into file
1022
            logMetacat.info("the inline element data is: "
1023
                    + inlineElements.toString());
1024
            writeInlineDataIntoFile(inlineDataFileWriter, inlineElements);
1025
        }//else
1026
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1027
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1028

    
1029
    }
1030

    
1031

    
1032
    /** SAX Handler that is called for each XML text node */
1033
    public void characters(char[] cbuf, int start, int len) throws SAXException
1034
    {
1035
        logMetacat.info("CHARACTERS");
1036
        if (!handleInlineData) {
1037
            // buffer all text nodes for same element. This is for text was
1038
            // splited
1039
            // into different nodes
1040
            textBuffer.append(new String(cbuf, start, len));
1041
            // set hittextnode true
1042
            hitTextNode = true;
1043
            // if text buffer .size is greater than max, write it to db.
1044
            // so we can save memory
1045
            if (textBuffer.length() >= MAXDATACHARS)
1046
            {
1047
                logMetacat.info("Write text into DB in charaters"
1048
                           + " when text buffer size is greater than maxmum number");
1049
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1050
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1051
                        currentNode);
1052
                if (needCheckingAccessModule
1053
                     && (processAdditionalAccess || processOtherAccess || processTopLeverAccess))
1054
                {
1055
                     // stored the pull out nodes into storedNode stack
1056
                     NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1057
                       null, null, MetaCatUtil.normalize(textBuffer
1058
                          .toString()));
1059
                     storedAccessNodeStack.push(nodeElement);
1060

    
1061
                }
1062
                textBuffer = null;
1063
                textBuffer = new StringBuffer();
1064
            }
1065
        }
1066
        else
1067
        {
1068
            // this is inline data and write file system directly
1069
            // we don't need to buffered it.
1070
            StringBuffer inlineText = new StringBuffer();
1071
            inlineText.append(new String(cbuf, start, len));
1072
            logMetacat.info(
1073
                    "The inline text data write into file system: "
1074
                            + inlineText.toString());
1075
            writeInlineDataIntoFile(inlineDataFileWriter, inlineText);
1076
        }
1077
    }
1078

    
1079
    /** SAX Handler that is called at the end of each XML element */
1080
    public void endElement(String uri, String localName, String qName)
1081
            throws SAXException
1082
    {
1083
        logMetacat.info("End ELEMENT " + qName);
1084

    
1085
        // when close inline element
1086
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1087
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1088
        if (localName.equals(INLINE) && handleInlineData)
1089
        {
1090
            // Get the node from the stack
1091
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1092
            String currentTag = currentNode.getTagName();
1093
            logMetacat.info("End of inline data");
1094
            // close file writer
1095
            try
1096
            {
1097
                inlineDataFileWriter.close();
1098
                handleInlineData = false;
1099
            }
1100
            catch (IOException ioe)
1101
            {
1102
                throw new SAXException(ioe.getMessage());
1103
            }
1104

    
1105
            //check if user changed inine data or not if user doesn't have
1106
            // write permission for this inline block
1107
            // if some error happends, we would delete the inline data file here,
1108
            // we will call a method named deletedInlineFiles in DocumentImple
1109
            if (unWritableInlineDataObject)
1110
            {
1111
                if (unReadableInlineDataObject)
1112
                {
1113
                  // now user just got a empty string in linline part
1114
                  // so if the user send back a empty string is fine and we will
1115
                  // copy the old file to new file. If he send something else,
1116
                  // the document will be rejected
1117
                  if (inlineDataIsEmpty(inlineDataFileName))
1118
                  {
1119
                    copyInlineFile(distributionId, inlineDataFileName);
1120
                  }
1121
                  else
1122
                  {
1123
                    logMetacat.info(
1124
                               "inline data was changed by a user"
1125
                                       + " who doesn't have permission");
1126
                    throw new SAXException(PERMISSIONERROR);
1127

    
1128
                  }
1129
                }//if
1130
                else
1131
                {
1132
                  // user get the inline data
1133
                  if (modifiedInlineData(distributionId, inlineDataFileName))
1134
                  {
1135
                    logMetacat.info(
1136
                                "inline data was changed by a user"
1137
                                        + " who doesn't have permission");
1138
                    throw new SAXException(PERMISSIONERROR);
1139
                  }//if
1140
                }//else
1141
            }//if
1142
            else
1143
            {
1144
               //now user can update file.
1145
               if (unReadableInlineDataObject)
1146
               {
1147
                  // now user just got a empty string in linline part
1148
                  // so if the user send back a empty string is fine and we will
1149
                  // copy the old file to new file. If he send something else,
1150
                  // the new inline data will overwite the old one(here we need
1151
                  // do nothing because the new inline data already existed
1152
                  if (inlineDataIsEmpty(inlineDataFileName))
1153
                  {
1154
                    copyInlineFile(distributionId, inlineDataFileName);
1155
                  }
1156
                }//if
1157

    
1158
            }//else
1159
            // put inline data file name into text buffer (without path)
1160
            textBuffer = new StringBuffer(inlineDataFileName);
1161
            // write file name into db
1162
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1163
                    currentNode);
1164
            // reset textbuff
1165
            textBuffer = null;
1166
            textBuffer = new StringBuffer();
1167
            // resetinlinedata file name
1168
            inlineDataFileName = null;
1169
            unWritableInlineDataObject = false;
1170
            unReadableInlineDataObject = false;
1171
            return;
1172
        }
1173
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1174
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1175

    
1176

    
1177

    
1178
        // close element which is not in inline data
1179
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1180
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1181
        if (!handleInlineData)
1182
        {
1183
            // Get the node from the stack
1184
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1185
            String currentTag = currentNode.getTagName();
1186

    
1187
            // If before the end element, the parser hit text nodes and store
1188
            // them
1189
            // into the buffer, write the buffer to data base. The reason we
1190
            // put
1191
            // write database here is for xerces some time split text node
1192
            if (hitTextNode)
1193
            {
1194
                // get access value
1195
                String data = null;
1196
                // add principal
1197
                if (currentTag.equals(PRINCIPAL) && accessRule != null)
1198
                {
1199
                    data = (textBuffer.toString()).trim();
1200
                    accessRule.addPrincipal(data);
1201

    
1202
                }
1203
                else if (currentTag.equals(PERMISSION) && accessRule != null)
1204
                {
1205
                    data = (textBuffer.toString()).trim();
1206
                    // we conbine different a permission into one value
1207
                    int permission = accessRule.getPermission();
1208
                    // add permision
1209
                    if (data.toUpperCase().equals(READSTRING))
1210
                    {
1211
                        permission = permission | READ;
1212
                    }
1213
                    else if (data.toUpperCase().equals(WRITESTRING))
1214
                    {
1215
                        permission = permission | WRITE;
1216
                    }
1217
                    else if (data.toUpperCase().equals(CHMODSTRING))
1218
                    {
1219
                        permission = permission | CHMOD;
1220
                    }
1221
                    else if (data.toUpperCase().equals(ALLSTRING))
1222
                    {
1223
                        permission = permission | ALL;
1224
                    }
1225
                    accessRule.setPermission(permission);
1226
                }
1227
                // put additionalmetadata/describes into vector
1228
                else if (currentTag.equals(DESCRIBES))
1229
                {
1230
                    data = (textBuffer.toString()).trim();
1231
                    describesId.add(data);
1232
                    //firstDescribesInAdditionalMetadata = false;
1233
                    //firstDescribesNodeId = 0;
1234
                }
1235
                else if (currentTag.equals(REFERENCES)
1236
                        && (processTopLeverAccess || processAdditionalAccess || processOtherAccess))
1237
                {
1238
                    // get reference
1239
                    data = (textBuffer.toString()).trim();
1240
                    // put reference id into accessSection
1241
                    accessObject.setReferences(data);
1242

    
1243
                }
1244
                else if (currentTag.equals(REFERENCES) && proccessDistribution)
1245
                {
1246
                  // get reference for distribution
1247
                  data = (textBuffer.toString()).trim();
1248
                  // we only stored the distribution reference which itself
1249
                  // has a id
1250
                  if (distributionId != null)
1251
                  {
1252
                    distributionReferenceList.put(distributionId, data);
1253
                  }
1254

    
1255
                }
1256
                else if (currentTag.equals(URL) && !inAddtionalMetaData)
1257
                {
1258
                    //handle online data, make sure its'parent is online
1259
                    DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1260
                    if (parentNode != null && parentNode.getTagName() != null
1261
                            && parentNode.getTagName().equals(ONLINE))
1262
                    {
1263
                        data = (textBuffer.toString()).trim();
1264
                        if (distributionId != null)
1265
                        {
1266
                          onlineURLDistributionIdList.put(distributionId, data);
1267
                        }
1268
                        else
1269
                        {
1270
                          onelineURLDistributionListWithoutId.add(data);
1271
                        }
1272
                    }//if
1273
                }//else if
1274
                // write text to db if it is not inline data
1275

    
1276
                logMetacat.info(
1277
                            "Write text into DB in End Element");
1278

    
1279
                 // write text node into db
1280
                 endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1281
                            currentNode);
1282

    
1283
                if (needCheckingAccessModule
1284
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1285
                    // stored the pull out nodes into storedNode stack
1286
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1287
                            null, null, MetaCatUtil.normalize(textBuffer
1288
                                    .toString()));
1289
                    storedAccessNodeStack.push(nodeElement);
1290

    
1291
                }
1292
            }//if handle text node
1293

    
1294

    
1295

    
1296
            //set hitText false
1297
            hitTextNode = false;
1298
            // reset textbuff
1299
            textBuffer = null;
1300
            textBuffer = new StringBuffer();
1301

    
1302

    
1303
            // access stuff
1304
            if (currentTag.equals(ALLOW) || currentTag.equals(DENY))
1305
            {
1306
                // finish parser a ccess rule and assign it to new one
1307
                AccessRule newRule = accessRule;
1308
                //add the new rule to access section object
1309
                accessObject.addAccessRule(newRule);
1310
                // reset access rule
1311
                accessRule = null;
1312
            }// ALLOW or DENY
1313
            else if (currentTag.equals(ACCESS))
1314
            {
1315
                // finish parse a access setction and stored them into different
1316
                // places
1317

    
1318
                accessObject.setEndNodeId(endNodeId);
1319
                AccessSection newAccessObject = accessObject;
1320
                newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
1321
                if (newAccessObject != null)
1322
                {
1323

    
1324
                    if (processTopLeverAccess)
1325
                    {
1326
                       topAccessSection = newAccessObject;
1327

    
1328
                    }//if
1329
                    else if (processAdditionalAccess)
1330
                    {
1331
                        // for additional control
1332
                        // put discribesId into the accessobject and put this
1333
                        // access object into vector
1334
                        newAccessObject.setDescribedIdList(describesId);
1335
                        addtionalAccessVector.add(newAccessObject);
1336

    
1337
                    }//if
1338
                    else if (processOtherAccess)
1339
                    {
1340
                      // we only stored the access object which has a id
1341
                      // because only the access object which has a id can
1342
                      // be reference
1343
                      if (newAccessObject.getSubTreeId() != null &&
1344
                          !newAccessObject.getSubTreeId().trim().equals(""))
1345
                      {
1346
                         possibleReferencedAccessHash.
1347
                           put(newAccessObject.getSubTreeId(), newAccessObject);
1348
                      }
1349
                    }
1350

    
1351
                }//if
1352
                //reset access section object
1353
                accessObject = null;
1354

    
1355
                // reset tmp stored node stack
1356
                storedAccessNodeStack = null;
1357
                storedAccessNodeStack = new Stack();
1358

    
1359
                // reset flag
1360
                processAdditionalAccess = false;
1361
                processTopLeverAccess = false;
1362
                processOtherAccess = false;
1363

    
1364
            }//access element
1365
            else if (currentTag.equals(ADDITIONALMETADATA))
1366
            {
1367
                //reset describesId
1368
                describesId = null;
1369
                describesId = new Vector();
1370
                inAddtionalMetaData = false;
1371
                firstDescribesNodeId = -1;
1372
                // reset tmp stored node stack
1373
                storedAccessNodeStack = null;
1374
                storedAccessNodeStack = new Stack();
1375

    
1376

    
1377
            }
1378
            else if (currentTag.equals(DISTRIBUTION) && !inAddtionalMetaData)
1379
            {
1380
               //reset distribution id
1381
               distributionId = null;
1382
               proccessDistribution = false;
1383
            }
1384
            else if (currentTag.equals(OFFLINE) && !inAddtionalMetaData)
1385
            {
1386
               if (distributionId != null)
1387
               {
1388
                 offlineDistributionIdList.put(distributionId, distributionId);
1389
               }
1390
            }
1391
            else if ((currentTag.equals(CONNECTION) || currentTag.equals(CONNECTIONDEFINITION))
1392
                     && !inAddtionalMetaData)
1393
            {
1394
              //handle online data, make sure its'parent is online
1395
                 DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1396
                 if (parentNode != null && parentNode.getTagName() != null
1397
                         && parentNode.getTagName().equals(ONLINE))
1398
                 {
1399
                     if (distributionId != null)
1400
                     {
1401
                        onlineOtherDistributionIdList.put(distributionId, distributionId);
1402
                     }
1403
                 }//if
1404

    
1405
            }//else if
1406
            else if (currentTag.equals(DESCRIBES))
1407
            {
1408
                firstDescribesInAdditionalMetadata = false;
1409

    
1410
            }
1411

    
1412

    
1413

    
1414
        }
1415
        // close elements which are in inline data (inline data can be xml doc)
1416
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1417
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1418
        else
1419
        {
1420
            // this is in inline part
1421
            StringBuffer endElement = new StringBuffer();
1422
            endElement.append("</");
1423
            endElement.append(qName);
1424
            endElement.append(">");
1425
            logMetacat.info("inline endElement: "
1426
                    + endElement.toString());
1427
            writeInlineDataIntoFile(inlineDataFileWriter, endElement);
1428
        }
1429
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1430
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1431
    }
1432

    
1433

    
1434
    /*
1435
     * Method to check if the new line data is as same as the old one
1436
     */
1437
     private boolean modifiedInlineData(String inlineDistributionId,
1438
			String newInlineInternalFileName) throws SAXException {
1439
       boolean modified = true;
1440
       if (inlineDistributionId == null || newInlineInternalFileName == null)
1441
       {
1442
         return modified;
1443
       }
1444
       String oldInlineInternalFileName =
1445
            (String)previousUnwritableInlineDataObjectHash.get(inlineDistributionId);
1446
       if (oldInlineInternalFileName == null ||
1447
           oldInlineInternalFileName.trim().equals(""))
1448
       {
1449
         return modified;
1450
       }
1451
       logMetacat.info("in handle inline data");
1452
       logMetacat.info("the inline data file name from xml_access is: "
1453
                                    + oldInlineInternalFileName);
1454

    
1455
       try
1456
       {
1457
         if (!compareInlineDataFiles(oldInlineInternalFileName,
1458
                                     newInlineInternalFileName))
1459
         {
1460
           modified = true;
1461

    
1462
         }
1463
         else
1464
         {
1465
           modified = false;
1466
         }
1467
       }
1468
       catch(Exception e)
1469
       {
1470
         modified = true;
1471
       }
1472

    
1473
       // delete the inline data file already in file system
1474
       if (modified)
1475
       {
1476
         deleteInlineDataFile(newInlineInternalFileName);
1477

    
1478
       }
1479
       return modified;
1480
     }
1481

    
1482
     /*
1483
      * A method to check if a line file is empty
1484
      */
1485
     private boolean inlineDataIsEmpty(String fileName) throws SAXException
1486
     {
1487
        boolean isEmpty = true;
1488
        if ( fileName == null)
1489
        {
1490
          throw new SAXException("The inline file name is null");
1491
        }
1492
        
1493
        try {
1494
			String path = PropertyService.getProperty("application.inlinedatafilepath");
1495
			// the new file name will look like path/docid.rev.2
1496
			File inlineDataDirectory = new File(path);
1497
			File inlineDataFile = new File(inlineDataDirectory, fileName);
1498

    
1499
			FileReader inlineFileReader = new FileReader(inlineDataFile);
1500
			BufferedReader inlineStringReader = new BufferedReader(inlineFileReader);
1501
			String string = inlineStringReader.readLine();
1502
			// at the end oldstring will be null
1503
			while (string != null) {
1504
				string = inlineStringReader.readLine();
1505
				if (string != null && !string.trim().equals("")) {
1506
					isEmpty = false;
1507
					break;
1508
				}
1509
			}
1510

    
1511
		} catch (Exception e) {
1512
			throw new SAXException(e.getMessage());
1513
		}
1514
		return isEmpty;
1515

    
1516
     }
1517

    
1518

    
1519
    /**
1520
	 * SAX Handler that receives notification of comments in the DTD
1521
	 */
1522
    public void comment(char[] ch, int start, int length) throws SAXException
1523
    {
1524
        logMetacat.info("COMMENT");
1525
        if (!handleInlineData) {
1526
            if (!processingDTD) {
1527
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1528
                String str = new String(ch, start, length);
1529

    
1530
                //compare comment if need
1531
                /*if (startCriticalSubTree) {
1532
                    compareCommentNode(currentUnChangedableSubtreeNodeStack,
1533
                            str, PERMISSIONERROR);
1534
                }//if*/
1535
                //compare top level access module
1536
                if (processTopLeverAccess && needCheckingAccessModule) {
1537
                    /*compareCommentNode(currentUnchangableAccessModuleNodeStack,
1538
                            str, UPDATEACCESSERROR);*/
1539
                }
1540
                endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
1541
                        str, docid);
1542
                if (needCheckingAccessModule
1543
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1544
                    // stored the pull out nodes into storedNode stack
1545
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2,
1546
                            "COMMENT", null, null, MetaCatUtil.normalize(str));
1547
                    storedAccessNodeStack.push(nodeElement);
1548

    
1549
                }
1550
            }
1551
        } else {
1552
            // inline data comment
1553
            StringBuffer inlineComment = new StringBuffer();
1554
            inlineComment.append("<!--");
1555
            inlineComment.append(new String(ch, start, length));
1556
            inlineComment.append("-->");
1557
            logMetacat.info("inline data comment: "
1558
                    + inlineComment.toString());
1559
            writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1560
        }
1561
    }
1562

    
1563

    
1564

    
1565
    /**
1566
     * SAX Handler called once for each processing instruction found: node that
1567
     * PI may occur before or after the root element.
1568
     */
1569
    public void processingInstruction(String target, String data)
1570
            throws SAXException
1571
    {
1572
        logMetacat.info("PI");
1573
        if (!handleInlineData) {
1574
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1575
            endNodeId = currentNode.writeChildNodeToDB("PI", target, data,
1576
                    docid);
1577
        } else {
1578
            StringBuffer inlinePI = new StringBuffer();
1579
            inlinePI.append("<?");
1580
            inlinePI.append(target);
1581
            inlinePI.append(" ");
1582
            inlinePI.append(data);
1583
            inlinePI.append("?>");
1584
            logMetacat.info("inline data pi is: "
1585
                    + inlinePI.toString());
1586
            writeInlineDataIntoFile(inlineDataFileWriter, inlinePI);
1587
        }
1588
    }
1589

    
1590
    /** SAX Handler that is called at the start of Namespace */
1591
    public void startPrefixMapping(String prefix, String uri)
1592
            throws SAXException
1593
    {
1594
        logMetacat.info("NAMESPACE");
1595
        logMetacat.info("NAMESPACE prefix "+prefix);
1596
        logMetacat.info("NAMESPACE uri "+uri);
1597
        if (!handleInlineData) {
1598
            namespaces.put(prefix, uri);
1599
        } else {
1600
            inlineDataNameSpace.put(prefix, uri);
1601
        }
1602
    }
1603

    
1604
    /**
1605
     * SAX Handler that is called for each XML text node that is Ignorable
1606
     * white space
1607
     */
1608
    public void ignorableWhitespace(char[] cbuf, int start, int len)
1609
            throws SAXException
1610
    {
1611
        // When validation is turned "on", white spaces are reported here
1612
        // When validation is turned "off" white spaces are not reported here,
1613
        // but through characters() callback
1614
        logMetacat.info("IGNORABLEWHITESPACE");
1615
        if (!handleInlineData) {
1616
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1617
            String data = null;
1618
            int leftover = len;
1619
            int offset = start;
1620
            boolean moredata = true;
1621

    
1622
            // This loop deals with the case where there are more characters
1623
            // than can fit in a single database text field (limit is
1624
            // MAXDATACHARS). If the text to be inserted exceeds MAXDATACHARS,
1625
            // write a series of nodes that are MAXDATACHARS long, and then the
1626
            // final node contains the remainder
1627
            while (moredata) {
1628
                if (leftover > MAXDATACHARS) {
1629
                    data = new String(cbuf, offset, MAXDATACHARS);
1630
                    leftover -= MAXDATACHARS;
1631
                    offset += MAXDATACHARS;
1632
                } else {
1633
                    data = new String(cbuf, offset, leftover);
1634
                    moredata = false;
1635
                }
1636

    
1637
                //compare whitespace if need
1638
                /*if (startCriticalSubTree) {
1639
                    compareWhiteSpace(currentUnChangedableSubtreeNodeStack,
1640
                            data, PERMISSIONERROR);
1641
                }//if*/
1642

    
1643
                //compare whitespace in access top module
1644
                if (processTopLeverAccess && needCheckingAccessModule) {
1645
                    /*compareWhiteSpace(currentUnchangableAccessModuleNodeStack,
1646
                            data, UPDATEACCESSERROR);*/
1647
                }
1648
                // Write the content of the node to the database
1649
                if (needCheckingAccessModule
1650
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1651
                    // stored the pull out nodes into storedNode stack
1652
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1653
                            null, null, MetaCatUtil.normalize(data));
1654
                    storedAccessNodeStack.push(nodeElement);
1655

    
1656
                }
1657
                endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
1658
                        docid);
1659
            }
1660
        } else {
1661
            //This is inline data write to file directly
1662
            StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf,
1663
                    start, len));
1664
            writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1665
        }
1666

    
1667
    }
1668

    
1669

    
1670
    /** SAX Handler that receives notification of end of the document */
1671
    public void endDocument() throws SAXException
1672
    {
1673
        logMetacat.info("end Document");
1674
        if (needCheckingAccessModule)
1675
        {
1676
          compareAllAccessModules();
1677
        }
1678

    
1679
        // user deleted some inline block which it counldn't delete
1680
        if (numberOfHitUnWritableInlineData !=
1681
            previousUnwritableInlineDataObjectHash.size())
1682
        {
1683
          throw new SAXException("user deleted some inline block it couldn't");
1684
        }
1685

    
1686
        if (!super.getIsRevisionDoc())
1687
        {
1688
          // write access rule to xml_access table which include both top level
1689
          // and additional level(data access level). It also write access subtree
1690
          // info into xml_accesssubtree about the top access, additional access
1691
          // and some third place access modules which are referenced by top
1692
          // level or additional level
1693
          writeAccessRuleToDB();
1694

    
1695
          //delete relation table
1696
          deleteRelations();
1697
          //write relations
1698
           for (int i = 0; i < onlineDataFileIdInRelationVector.size(); i++) {
1699
            String id = (String) onlineDataFileIdInRelationVector.elementAt(i);
1700
            writeOnlineDataFileIdIntoRelationTable(id);
1701
           }
1702
        }
1703

    
1704
        // clean the subtree record
1705
        accessSubTreeAlreadyWriteDBList = new Hashtable();
1706
    }
1707

    
1708

    
1709

    
1710
    /* The method will compare all access modules in eml document -
1711
     * topLevel, additionalLevel(data access) and referenced access module*/
1712
    private void compareAllAccessModules() throws SAXException
1713
    {
1714
      //compare top level
1715
      compareAccessSubtree(unChangebleTopAccessSubTree, topAccessSection);
1716

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

    
1736
      //compare referenced level
1737
      Enumeration em = unChangebleReferencedAccessSubTreeHash.keys();
1738
      while (em.hasMoreElements())
1739
      {
1740
        String id = (String)em.nextElement();
1741
        AccessSection fromDB = (AccessSection)
1742
                               unChangebleReferencedAccessSubTreeHash.get(id);
1743
        AccessSection fromParser = (AccessSection)
1744
                               possibleReferencedAccessHash.get(id);
1745
        compareAccessSubtree(fromDB, fromParser);
1746
      }
1747
    }
1748

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

    
1764
       Stack tempStack = new Stack();
1765
       while(!nodeStackFromDBTable.isEmpty()){
1766
           tempStack.push(nodeStackFromDBTable.pop());
1767
       }
1768
       comparingNodeStacks(tempStack, nodeStackFromParser);
1769
    }
1770

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

    
1785
          // Pop an element from stack2(stack 2 maybe empty)
1786
          NodeRecord record2 = null;
1787
          try {
1788
              record2 = (NodeRecord) stack2.pop();
1789
          } catch (EmptyStackException ee) {
1790

    
1791
              logMetacat.error(
1792
                      "Node stack2 is empty but stack1 isn't!");
1793
              throw new SAXException(UPDATEACCESSERROR);
1794
          }
1795
          // if two records are not same throw a exception
1796
          if (!record1.contentEquals(record2)) {
1797
              logMetacat.info("Two records from new and old stack are not "
1798
                                      + "same!" + record1 + "--" +record2);
1799
              throw new SAXException(UPDATEACCESSERROR);
1800
          }//if
1801
      }//while
1802

    
1803
      // now stack1 is empty and we should make sure stack2 is empty too
1804
      if (!stack2.isEmpty()) {
1805

    
1806
          logMetacat.info(
1807
                  "stack2 still have some elements while stack1 "
1808
                          + "is empty! ");
1809
          throw new SAXException(UPDATEACCESSERROR);
1810
      }//if
1811
  }//comparingNodeStacks
1812

    
1813

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

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

    
1833

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

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

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

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

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

    
1940

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

    
1966
       if (describeIdList == null || describeIdList.isEmpty())
1967
       {
1968
         continue;
1969
       }
1970

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

    
2024
   }//writeAdditonalLevelAccessRuletoDB
2025

    
2026

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

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

    
2066
         }
2067
       }//while
2068

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

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

    
2104
       try
2105
       {
2106

    
2107
           pstmt = connection.prepareStatement(sql);
2108
           // Increase DBConnection usage count
2109
           connection.increaseUsageCount(1);
2110
           // Bind the values to the query
2111
           pstmt.setString(1, dataId);
2112
           logMetacat.info("Docid in accesstable: " + docid);
2113
           pstmt.setString(6, docid);
2114
           logMetacat.info("Accessfileid in accesstable: " + docid);
2115
           pstmt.setString(5, permOrder);
2116
           logMetacat.info("PermOder in accesstable: " + permOrder);
2117
           pstmt.setString(7, subTreeId);
2118
           logMetacat.info("subtree id in accesstable: " + subTreeId);
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
               logMetacat.info("permission in accesstable: "
2130
                       + permission);
2131
               pstmt.setString(4, permType);
2132
               logMetacat.info(
2133
                       "Permtype in accesstable: " + permType);
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
                   logMetacat.info("Principal in accesstable: "
2141
                           + prName);
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
          logMetacat.info("Access object is null and tried to write "+
2263
                                   "into access subtree table");
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
            logMetacat.info("Docid in access-subtreetable: " + docid);
2312
            pstmt.setInt(2, (new Integer(revision)).intValue());
2313
            logMetacat.info("rev in accesssubtreetable: " + revision);
2314
            pstmt.setString(3, level);
2315
            logMetacat.info("contorl level in access-subtree table: "
2316
                    + level);
2317
            pstmt.setString(4, sectionId);
2318
            logMetacat.info("Subtree id in access-subtree table: "
2319
                    + sectionId);
2320
            pstmt.setLong(5, startNodeId);
2321
            logMetacat.info("Start node id is: " + startNodeId);
2322
            pstmt.setLong(6, endNodeId);
2323
            logMetacat.info("End node id is: " + endNodeId);
2324
            pstmt.execute();
2325
            pstmt.close();
2326
        }//try
2327
        catch (SQLException e)
2328
        {
2329
            throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2330
                    + e.getMessage());
2331
        }//catch
2332
        finally
2333
        {
2334
            try
2335
            {
2336
                pstmt.close();
2337
            }
2338
            catch (SQLException ee)
2339
            {
2340
                throw new SAXException(
2341
                        "EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2342
                                + ee.getMessage());
2343
            }
2344
        }//finally
2345

    
2346
    }//writeAccessSubtreeIntoDB
2347

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

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

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

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

    
2408

    
2409

    
2410
    /*
2411
     * In eml2, the inline data wouldn't store in db, it store in file system
2412
     * The db stores file name(without path). We got the old file name from db
2413
     * and compare to the new in line data file
2414
     */
2415
    public boolean compareInlineDataFiles(String oldFileName, String newFileName)
2416
            throws McdbException
2417
    {
2418
        // this method need to be testing
2419
        boolean same = true;
2420
        String data = null;
2421
        try {
2422
        	String path = PropertyService.getProperty("application.inlinedatafilepath");
2423
			// the new file name will look like path/docid.rev.2
2424
			File inlineDataDirectory = new File(path);
2425
			File oldDataFile = new File(inlineDataDirectory, oldFileName);
2426
			File newDataFile = new File(inlineDataDirectory, newFileName);
2427

    
2428
            FileReader oldFileReader = new FileReader(oldDataFile);
2429
            BufferedReader oldStringReader = new BufferedReader(oldFileReader);
2430
            FileReader newFileReader = new FileReader(newDataFile);
2431
            BufferedReader newStringReader = new BufferedReader(newFileReader);
2432
            // read first line of data
2433
            String oldString = oldStringReader.readLine();
2434
            String newString = newStringReader.readLine();
2435

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

    
2446
            // if oldString is null but newString is not null, they are same
2447
            if (same) {
2448
                if (newString != null) {
2449
                    same = false;
2450
                }
2451
            }
2452

    
2453
        } catch (Exception e) {
2454
            throw new McdbException(e.getMessage());
2455
        }
2456
        logMetacat.info("the inline data retrieve from file: " + data);
2457
        return same;
2458
    }
2459

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

    
2473
		if (oldInlineInternalFileName == null
2474
				|| oldInlineInternalFileName.trim().equals("")) {
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
		logMetacat.info("in handle inline data");
2479
		logMetacat.info("the inline data file name from xml_access is: "
2480
				+ oldInlineInternalFileName);
2481

    
2482
		FileReader oldFileReader = null;
2483
		FileWriter newFileWriter = null;
2484
		try {
2485
			String path = PropertyService.getProperty("application.inlinedatafilepath");
2486
			// the new file name will look like path/docid.rev.2
2487
			File inlineDataDirectory = new File(path);
2488
			File oldDataFile = new File(inlineDataDirectory, oldInlineInternalFileName);
2489
			File newDataFile = new File(inlineDataDirectory, newFileName);
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
				newFileWriter.write(buf, 0, b);
2497
				b = oldFileReader.read(buf);
2498
			}
2499
		} catch (Exception e) {
2500
			throw new SAXException(e.getMessage());
2501
		} finally {
2502
			if (oldFileReader != null) {
2503
				try {
2504
					oldFileReader.close();
2505
				} catch (Exception ee) {
2506
					throw new SAXException(ee.getMessage());
2507
				}
2508

    
2509
			}
2510
			if (newFileWriter != null) {
2511
				try {
2512
					newFileWriter.close();
2513
				} catch (Exception ee) {
2514
					throw new SAXException(ee.getMessage());
2515
				}
2516

    
2517
			}
2518
		}
2519
	}
2520

    
2521

    
2522
    // if xml file failed to upload, we need to call this method to delete
2523
    // the inline data already in file system
2524
    public void deleteInlineFiles() throws SAXException
2525
    {
2526
        if (!inlineFileIDList.isEmpty()) {
2527
            for (int i = 0; i < inlineFileIDList.size(); i++) {
2528
                String fileName = (String) inlineFileIDList.elementAt(i);
2529
                deleteInlineDataFile(fileName);
2530
            }
2531
        }
2532
    }
2533

    
2534
    /* delete the inline data file */
2535
    private void deleteInlineDataFile(String fileName) throws SAXException
2536
    {
2537
    	String path;
2538
    	try {
2539
    		path = PropertyService.getProperty("application.inlinedatafilepath");
2540
    	} catch (PropertyNotFoundException pnfe) {
2541
    		throw new SAXException ("Could not find inline data file path: " 
2542
    				+ pnfe.getMessage());
2543
    	}
2544
        File inlineDataDirectory = new File(path);
2545
        File newFile = new File(inlineDataDirectory, fileName);
2546
        newFile.delete();
2547

    
2548
    }
2549

    
2550
    /*
2551
	 * In eml2, the inline data wouldn't store in db, it store in file system
2552
	 * The db stores file name(without path).
2553
	 */
2554
	public static Reader readInlineDataFromFileSystem(String fileName)
2555
			throws McdbException {
2556
		// BufferedReader stringReader = null;
2557
		FileReader fileReader = null;
2558
		try {
2559
			String path = PropertyService.getProperty("application.inlinedatafilepath");
2560
			// the new file name will look like path/docid.rev.2
2561
			File inlineDataDirectory = new File(path);
2562
			File dataFile = new File(inlineDataDirectory, fileName);
2563

    
2564
			fileReader = new FileReader(dataFile);
2565
			// stringReader = new BufferedReader(fileReader);
2566
		} catch (Exception e) {
2567
			throw new McdbException(e.getMessage());
2568
		}
2569
		// return stringReader;
2570
		return fileReader;
2571
	}
2572

    
2573
    /* Delete relations */
2574
    private void deleteRelations() throws SAXException
2575
    {
2576
        PreparedStatement pStmt = null;
2577
        String sql = "DELETE FROM xml_relation where docid =?";
2578
        try {
2579
            pStmt = connection.prepareStatement(sql);
2580
            //bind variable
2581
            pStmt.setString(1, docid);
2582
            //execute query
2583
            pStmt.execute();
2584
            pStmt.close();
2585
        }//try
2586
        catch (SQLException e) {
2587
            throw new SAXException("EMLSAXHandler.deleteRelations(): "
2588
                    + e.getMessage());
2589
        }//catch
2590
        finally {
2591
            try {
2592
                pStmt.close();
2593
            }//try
2594
            catch (SQLException ee) {
2595
                throw new SAXException("EMLSAXHandler.deleteRelations: "
2596
                        + ee.getMessage());
2597
            }//catch
2598
        }//finally
2599
    }
2600

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

    
2638
    }//writeOnlineDataFileIdIntoRelationTable
2639

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

    
2667
          if (!AccessionNumber.accNumberUsed(docid))
2668
          {
2669
            return docid;
2670
          }
2671
          PermissionController controller = new
2672
              PermissionController(accessionNumber);
2673
          if (controller.hasPermission(
2674
              user, groups, AccessControlInterface.ALLSTRING))
2675
          {
2676
            return docid;
2677
          }
2678
          else
2679
          {
2680
            throw new SAXException("User does not have permission to update " +
2681
                  "of access rules for data file "+ docid);
2682
          }
2683
        }//try
2684
        catch(Exception e)
2685
        {
2686
          logMetacat.error("Error in " +
2687
                                "Eml200SAXHanlder.handleOnlineUrlDataFile is " +
2688
                                 e.getMessage());
2689
          throw new SAXException(e.getMessage());
2690
        }
2691
      }
2692
      return docid;
2693
    }
2694

    
2695
    private void compareElementNameSpaceAttributes(Stack unchangableNodeStack,
2696
            Hashtable nameSpaces, Attributes attributes, String localName,
2697
            String error) throws SAXException
2698
    {
2699
        //Get element subtree node stack (element node)
2700
        NodeRecord elementNode = null;
2701
        try {
2702
            elementNode = (NodeRecord) unchangableNodeStack.pop();
2703
        } catch (EmptyStackException ee) {
2704
            logMetacat.error("Node stack is empty for element data");
2705
            throw new SAXException(error);
2706
        }
2707
        logMetacat.info("current node type from xml is ELEMENT");
2708
        logMetacat.info("node type from stack: "
2709
                + elementNode.getNodeType());
2710
        logMetacat.info("node name from xml document: " + localName);
2711
        logMetacat.info("node name from stack: "
2712
                + elementNode.getNodeName());
2713
        logMetacat.info("node data from stack: "
2714
                + elementNode.getNodeData());
2715
        logMetacat.info("node id is: " + elementNode.getNodeId());
2716
        // if this node is not element or local name not equal or name space
2717
        // not
2718
        // equals, throw an exception
2719
        if (!elementNode.getNodeType().equals("ELEMENT")
2720
                || !localName.equals(elementNode.getNodeName()))
2721
        //  (uri != null && !uri.equals(elementNode.getNodePrefix())))
2722
        {
2723
            logMetacat.info("Inconsistence happend: ");
2724
            logMetacat.info("current node type from xml is ELEMENT");
2725
            logMetacat.info("node type from stack: "
2726
                    + elementNode.getNodeType());
2727
            logMetacat.info("node name from xml document: "
2728
                    + localName);
2729
            logMetacat.info("node name from stack: "
2730
                    + elementNode.getNodeName());
2731
            logMetacat.info("node data from stack: "
2732
                    + elementNode.getNodeData());
2733
            logMetacat.info("node id is: " + elementNode.getNodeId());
2734
            throw new SAXException(error);
2735
        }
2736

    
2737
        //compare namespace
2738
        Enumeration nameEn = nameSpaces.keys();
2739
        while (nameEn.hasMoreElements()) {
2740
            //Get namespacke node stack (element node)
2741
            NodeRecord nameNode = null;
2742
            try {
2743
                nameNode = (NodeRecord) unchangableNodeStack.pop();
2744
            } catch (EmptyStackException ee) {
2745
                logMetacat.error(
2746
                        "Node stack is empty for namespace data");
2747
                throw new SAXException(error);
2748
            }
2749

    
2750
            String prefixName = (String) nameEn.nextElement();
2751
            String nameSpaceUri = (String) nameSpaces.get(prefixName);
2752
            if (!nameNode.getNodeType().equals("NAMESPACE")
2753
                    || !prefixName.equals(nameNode.getNodeName())
2754
                    || !nameSpaceUri.equals(nameNode.getNodeData())) {
2755
                logMetacat.info("Inconsistence happend: ");
2756
                logMetacat.info(
2757
                        "current node type from xml is NAMESPACE");
2758
                logMetacat.info("node type from stack: "
2759
                        + nameNode.getNodeType());
2760
                logMetacat.info("current node name from xml is: "
2761
                        + prefixName);
2762
                logMetacat.info("node name from stack: "
2763
                        + nameNode.getNodeName());
2764
                logMetacat.info("current node data from xml is: "
2765
                        + nameSpaceUri);
2766
                logMetacat.info("node data from stack: "
2767
                        + nameNode.getNodeData());
2768
                logMetacat.info("node id is: " + nameNode.getNodeId());
2769
                throw new SAXException(error);
2770
            }
2771

    
2772
        }//while
2773

    
2774
        //compare attributes
2775
        for (int i = 0; i < attributes.getLength(); i++) {
2776
            NodeRecord attriNode = null;
2777
            try {
2778
                attriNode = (NodeRecord) unchangableNodeStack.pop();
2779

    
2780
            } catch (EmptyStackException ee) {
2781
                logMetacat.error(
2782
                        "Node stack is empty for attribute data");
2783
                throw new SAXException(error);
2784
            }
2785
            String attributeName = attributes.getQName(i);
2786
            String attributeValue = attributes.getValue(i);
2787
            logMetacat.info(
2788
                    "current node type from xml is ATTRIBUTE ");
2789
            logMetacat.info("node type from stack: "
2790
                    + attriNode.getNodeType());
2791
            logMetacat.info("current node name from xml is: "
2792
                    + attributeName);
2793
            logMetacat.info("node name from stack: "
2794
                    + attriNode.getNodeName());
2795
            logMetacat.info("current node data from xml is: "
2796
                    + attributeValue);
2797
            logMetacat.info("node data from stack: "
2798
                    + attriNode.getNodeData());
2799
            logMetacat.info("node id  is: " + attriNode.getNodeId());
2800

    
2801
            if (!attriNode.getNodeType().equals("ATTRIBUTE")
2802
                    || !attributeName.equals(attriNode.getNodeName())
2803
                    || !attributeValue.equals(attriNode.getNodeData())) {
2804
                logMetacat.info("Inconsistence happend: ");
2805
                logMetacat.info(
2806
                        "current node type from xml is ATTRIBUTE ");
2807
                logMetacat.info("node type from stack: "
2808
                        + attriNode.getNodeType());
2809
                logMetacat.info("current node name from xml is: "
2810
                        + attributeName);
2811
                logMetacat.info("node name from stack: "
2812
                        + attriNode.getNodeName());
2813
                logMetacat.info("current node data from xml is: "
2814
                        + attributeValue);
2815
                logMetacat.info("node data from stack: "
2816
                        + attriNode.getNodeData());
2817
                logMetacat.info("node is: " + attriNode.getNodeId());
2818
                throw new SAXException(error);
2819
            }
2820
        }//for
2821

    
2822
    }
2823

    
2824
    /* mehtod to compare current text node and node in db */
2825
    private void compareTextNode(Stack nodeStack, StringBuffer text,
2826
            String error) throws SAXException
2827
    {
2828
        NodeRecord node = null;
2829
        //get node from current stack
2830
        try {
2831
            node = (NodeRecord) nodeStack.pop();
2832
        } catch (EmptyStackException ee) {
2833
            logMetacat.error(
2834
                    "Node stack is empty for text data in startElement");
2835
            throw new SAXException(error);
2836
        }
2837
        logMetacat.info(
2838
                "current node type from xml is TEXT in start element");
2839
        logMetacat.info("node type from stack: " + node.getNodeType());
2840
        logMetacat.info("current node data from xml is: "
2841
                + text.toString());
2842
        logMetacat.info("node data from stack: " + node.getNodeData());
2843
        logMetacat.info("node name from stack: " + node.getNodeName());
2844
        logMetacat.info("node is: " + node.getNodeId());
2845
        if (!node.getNodeType().equals("TEXT")
2846
                || !(text.toString()).equals(node.getNodeData())) {
2847
            logMetacat.info("Inconsistence happend: ");
2848
            logMetacat.info(
2849
                    "current node type from xml is TEXT in start element");
2850
            logMetacat.info("node type from stack: "
2851
                    + node.getNodeType());
2852
            logMetacat.info("current node data from xml is: "
2853
                    + text.toString());
2854
            logMetacat.info("node data from stack: "
2855
                    + node.getNodeData());
2856
            logMetacat.info("node name from stack: "
2857
                    + node.getNodeName());
2858
            logMetacat.info("node is: " + node.getNodeId());
2859
            throw new SAXException(error);
2860
        }//if
2861
    }
2862

    
2863
    /* Comparet comment from xml and db */
2864
    private void compareCommentNode(Stack nodeStack, String string, String error)
2865
            throws SAXException
2866
    {
2867
        NodeRecord node = null;
2868
        try {
2869
            node = (NodeRecord) nodeStack.pop();
2870
        } catch (EmptyStackException ee) {
2871
            logMetacat.error("the stack is empty for comment data");
2872
            throw new SAXException(error);
2873
        }
2874
        logMetacat.info("current node type from xml is COMMENT");
2875
        logMetacat.info("node type from stack: " + node.getNodeType());
2876
        logMetacat.info("current node data from xml is: " + string);
2877
        logMetacat.info("node data from stack: " + node.getNodeData());
2878
        logMetacat.info("node is from stack: " + node.getNodeId());
2879
        // if not consistent terminate program and throw a exception
2880
        if (!node.getNodeType().equals("COMMENT")
2881
                || !string.equals(node.getNodeData())) {
2882
            logMetacat.info("Inconsistence happend: ");
2883
            logMetacat.info("current node type from xml is COMMENT");
2884
            logMetacat.info("node type from stack: "
2885
                    + node.getNodeType());
2886
            logMetacat.info(
2887
                    "current node data from xml is: " + string);
2888
            logMetacat.info("node data from stack: "
2889
                    + node.getNodeData());
2890
            logMetacat.info("node is from stack: " + node.getNodeId());
2891
            throw new SAXException(error);
2892
        }//if
2893
    }
2894

    
2895
    /* Compare whitespace from xml and db */
2896
   private void compareWhiteSpace(Stack nodeStack, String string, String error)
2897
           throws SAXException
2898
   {
2899
       NodeRecord node = null;
2900
       try {
2901
           node = (NodeRecord) nodeStack.pop();
2902
       } catch (EmptyStackException ee) {
2903
           logMetacat.error("the stack is empty for whitespace data");
2904
           throw new SAXException(error);
2905
       }
2906
       if (!node.getNodeType().equals("TEXT")
2907
               || !string.equals(node.getNodeData())) {
2908
           logMetacat.info("Inconsistence happend: ");
2909
           logMetacat.info(
2910
                   "current node type from xml is WHITESPACE TEXT");
2911
           logMetacat.info("node type from stack: "
2912
                   + node.getNodeType());
2913
           logMetacat.info(
2914
                   "current node data from xml is: " + string);
2915
           logMetacat.info("node data from stack: "
2916
                   + node.getNodeData());
2917
           logMetacat.info("node is from stack: " + node.getNodeId());
2918
           throw new SAXException(error);
2919
       }//if
2920
   }
2921

    
2922

    
2923

    
2924
}
(35-35/67)