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: leinfelder $'
10
 *     '$Date: 2011-11-02 20:40:12 -0700 (Wed, 02 Nov 2011) $'
11
 * '$Revision: 6595 $'
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.File;
32
import java.io.FileInputStream;
33
import java.io.FileOutputStream;
34
import java.io.IOException;
35
import java.io.InputStream;
36
import java.io.InputStreamReader;
37
import java.io.OutputStream;
38
import java.io.OutputStreamWriter;
39
import java.io.Reader;
40
import java.io.Writer;
41
import java.sql.PreparedStatement;
42
import java.sql.ResultSet;
43
import java.sql.SQLException;
44
import java.sql.Statement;
45
import java.util.Date;
46
import java.util.EmptyStackException;
47
import java.util.Enumeration;
48
import java.util.Hashtable;
49
import java.util.Stack;
50
import java.util.Vector;
51

    
52
import org.apache.log4j.Logger;
53
import org.xml.sax.Attributes;
54
import org.xml.sax.SAXException;
55

    
56
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
57
import edu.ucsb.nceas.metacat.accesscontrol.AccessRule;
58
import edu.ucsb.nceas.metacat.accesscontrol.AccessSection;
59
import edu.ucsb.nceas.metacat.database.DBConnection;
60
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
61
import edu.ucsb.nceas.metacat.properties.PropertyService;
62
import edu.ucsb.nceas.metacat.util.AuthUtil;
63
import edu.ucsb.nceas.metacat.util.DocumentUtil;
64
import edu.ucsb.nceas.metacat.util.MetacatUtil;
65
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
66

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

    
131
    // now additionalAccess will be explained as distribution access control
132
    // - data file
133
    private boolean processAdditionalAccess = false;
134

    
135
	// Boolean that tells whether we are processing other access. This is true when 
136
    // we find an 'access' element inside an 'additionalMetadata' element.  Set back
137
    // to false in endElement
138
    private boolean processOtherAccess = false;
139

    
140
    // if we are inside an 'access' element, we use this object to hold the 
141
    // current access info
142
    private AccessSection accessObject = null;
143

    
144
    // for each 'access/allow' and 'access/deny' we create a new access Rule to hold
145
    // the info
146
    private AccessRule accessRule = null;
147

    
148
    private Vector describesId = new Vector(); // store the ids in
149
                                               //additionalmetadata/describes
150

    
151
    //store all distribution element id for online url. key is the distribution
152
    // id and  data  is url
153
    private Hashtable onlineURLDistributionIdList = new Hashtable();
154
    // distribution/oneline/url will store this vector if distribution doesn't
155
    // have a id.
156
    private Vector onlineURLDistributionListWithoutId = new Vector();
157

    
158
    //store all distribution element id for online other distribution, such as
159
    // connection or connectiondefination. key is the distribution id
160
    // and  data  is distribution id
161
    private Hashtable onlineOtherDistributionIdList = new Hashtable();
162

    
163
    //store all distribution element id for inline data.
164
    // key is the distribution id, data is the internal inline id
165
    private Hashtable inlineDistributionIdList = new Hashtable();
166

    
167
    //store all distribution element id for off line data.
168
    // key is the distribution id, data is the id too.
169
    private Hashtable offlineDistributionIdList = new Hashtable();
170

    
171
    // a hash to stored all distribution id, both key and value are id itself
172
    private Hashtable distributionAllIdList = new Hashtable();
173

    
174
    // temporarily store distribution id
175
    private String distributionId = null;
176

    
177
    // flag to indicate to handle distribution
178
    private boolean proccessDistribution = false;
179

    
180
    // a hash table to stored the distribution which is a reference and this
181
    // distribution has a id too. The key is itself id of this distribution,
182
    // the value is the referenced id.
183
    // So, we only stored the format like this:
184
    // <distribution id ="100"><reference>300</reference></distribution>
185
    // the reason is:
186
    // if not id in distribution, then the distribution couldn't be added
187
    // to additional access module. The distribution block which was referenced
188
    // id (300) will be stored in above distribution lists.
189
    private Hashtable distributionReferenceList = new Hashtable();
190

    
191
    // if the action is update and the user does not have ALL permission 
192
    // and the user is not an administrator, then we will need to compare 
193
    // access modules to make sure the user has update permissions
194
    private boolean needToCheckAccessModule = false;
195

    
196
    private AccessSection topAccessSubTreeFromDB = null;
197

    
198
    private Vector additionalAccessSubTreeListFromDB = new Vector();
199

    
200
    private Hashtable referencedAccessSubTreeListFromDB = new Hashtable();
201

    
202
    // this holds the top level (document level) access section.
203
    private AccessSection topAccessSection;
204

    
205
    private Vector additionalAccessVector = new Vector();
206

    
207
    // key is subtree id and value is accessSection object
208
    private Hashtable possibleReferencedAccessHash = new Hashtable();
209

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

    
214
    // vector stored the data file id which will be write into relation table
215
    private Vector onlineDataFileIdInRelationVector = new Vector();
216

    
217
    // Indicator of inline data
218
    private boolean handleInlineData = false;
219

    
220
    private Hashtable inlineDataNameSpace = null;
221

    
222
    private Writer inlineDataFileWriter = null;
223

    
224
    private String inlineDataFileName = null;
225

    
226
    private int inLineDataIndex = 0;
227

    
228
    private Vector inlineFileIDList = new Vector();
229

    
230
    private boolean inAdditionalMetaData = false;
231

    
232
    //user has unwritable inline data object when it updates a document
233
    private boolean unWritableInlineDataObject = false;
234
    //user has unreadable inline data when it updates a dcoument
235
    private boolean unReadableInlineDataObject = false;
236

    
237
    // the hashtable contains the info from xml_access table which
238
    // inline data the user can't read when user update a document.
239
    // The key in hashtable is subtree id and data is the inline data internal
240
    // file name.
241

    
242
    private Hashtable previousUnreadableInlineDataObjectHash = new Hashtable();
243

    
244
    // the hashtable contains the info from xml_access table which
245
    // inline data the user can't write when user update a document.
246
    // The key in hashtable is subtree id and data is the inline data internal
247
    // file name.
248
    private Hashtable previousUnwritableInlineDataObjectHash = new Hashtable();
249

    
250
    private Hashtable accessSubTreeAlreadyWriteDBList = new Hashtable();
251

    
252
    //This hashtable will stored the id which already has additional access
253
    // control. So the top level access control will ignore them.
254
    private Hashtable onlineURLIdHasadditionalAccess   = new Hashtable();
255

    
256
    // additional access module will be in additionalMetadata part. Its format
257
    // look like
258
    //<additionalMetadata>
259
    //   <describes>100</describes>
260
    //   <describes>300</describes>
261
    //   <access>rulesone</access>
262
    //</additionalMetadata>
263
    // If user couldn't have all permission to update access rules, he/she could
264
    // not update access module, but also couldn't update "describes".
265
    // So the start node id for additional access section is the first describes
266
    // element
267
    private boolean firstDescribesInAdditionalMetadata = true;
268
    private long    firstDescribesNodeId               = -1;
269

    
270
    private int numberOfHitUnWritableInlineData = 0;
271

    
272
    // Constant
273
    private static final String EML = "eml";
274

    
275
    private static final String DESCRIBES = "describes";
276

    
277
    private static final String ADDITIONALMETADATA = "additionalMetadata";
278

    
279
    private static final String ORDER = "order";
280

    
281
    private static final String ID = "id";
282

    
283
    private static final String REFERENCES = "references";
284

    
285
    public static final String INLINE = "inline";
286

    
287
    private static final String ONLINE = "online";
288

    
289
    private static final String OFFLINE = "offline";
290

    
291
    private static final String CONNECTION = "connection";
292

    
293
    private static final String CONNECTIONDEFINITION = "connectionDefinition";
294

    
295
    private static final String URL = "url";
296

    
297
    private static final String PERMISSIONERROR = "User tried to update a subtree "
298
        + "when they don't have write permission!";
299

    
300
    private static final String UPDATEACCESSERROR = "User tried to update an "
301
        + "access module when they don't have \"ALL\" permission!";
302

    
303
    public static final String TOPLEVEL = "top";
304

    
305
    public static final String DATAACCESSLEVEL = "dataAccess";
306

    
307
    // this level is for the access module which is not in top or additional
308
    // place, but it was referenced by top or additional
309
    private static final String REFERENCEDLEVEL = "referenced";
310

    
311
    private static final String RELATION = "Provides info for";
312

    
313
    private static final String DISTRIBUTION = "distribution";
314

    
315
    private Logger logMetacat = Logger.getLogger(Eml200SAXHandler.class);   	   	
316
    
317
    /**
318
     * Construct an instance of the handler class In this constructor, user can
319
     * specify the version need to upadate
320
     *
321
     * @param conn the JDBC connection to which information is written
322
     * @param action - "INSERT" or "UPDATE"
323
     * @param docid to be inserted or updated into JDBC connection
324
     * @param revision, the user specified the revision need to be update
325
     * @param user the user connected to MetaCat servlet and owns the document
326
     * @param groups the groups to which user belongs
327
     * @param pub flag for public "read" access on document
328
     * @param serverCode the serverid from xml_replication on which this
329
     *            document resides.
330
     *
331
     */
332
    public Eml200SAXHandler(DBConnection conn, String action, String docid,
333
            String revision, String user, String[] groups, String pub,
334
            int serverCode, Date createDate, Date updateDate) throws SAXException
335
    {
336
        super(conn, action, docid, revision, user, groups, pub, 
337
                serverCode, createDate, updateDate);
338
        // Get the unchangable subtrees (user doesn't have write permission)
339
        try
340
        {
341
            PermissionController control = new PermissionController(docid
342
                    + PropertyService.getProperty("document.accNumSeparator") + revision);
343
            //unChangableSubTreeHash = getUnchangableSubTree(control, user,
344
            // groups);
345

    
346
            // If the action is update and user doesn't have "ALL" permission
347
            // we need to check if user update access subtree
348
            if (action != null && action.equals("UPDATE")
349
                    && !control.hasPermission(user, groups,
350
                            AccessControlInterface.ALLSTRING) 
351
                            && !AuthUtil.isAdministrator(user, groups))
352
            {
353
                needToCheckAccessModule = true;
354
                topAccessSubTreeFromDB = getTopAccessSubTreeFromDB();
355
                additionalAccessSubTreeListFromDB =
356
                                         getAdditionalAccessSubTreeListFromDB();
357
                referencedAccessSubTreeListFromDB =
358
                                         getReferencedAccessSubTreeListFromDB();
359
            }
360

    
361
            //Here is for  data object checking.
362
            if (action != null && action.equals("UPDATE"))
363
            {
364
              //info about inline data object which user doesn't have read
365
              //permission the info come from xml_access table
366
              previousUnreadableInlineDataObjectHash = PermissionController.
367
                            getUnReadableInlineDataIdList(docid, user,
368
                                                          groups, true);
369

    
370
              //info about data object which user doesn't have write permission
371
              // the info come from xml_accesss table
372
              previousUnwritableInlineDataObjectHash = PermissionController.
373
                            getUnWritableInlineDataIdList(docid, user,
374
                                                          groups, true);
375

    
376
            }
377

    
378

    
379
        }
380
        catch (Exception e)
381
        {
382
            logMetacat.error("error in Eml200SAXHandler is " + e.getMessage());
383
            throw new SAXException(e.getMessage());
384
        }
385
    }
386

    
387
    /*
388
     * Get the top level access subtree info from xml_accesssubtree table.
389
     * If no top access subtree found, null will be return.
390
     */
391
     private AccessSection getTopAccessSubTreeFromDB()
392
                                                       throws SAXException
393
     {
394
       AccessSection topAccess = null;
395
       PreparedStatement pstmt = null;
396
       ResultSet rs = null;
397
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
398
                + "FROM xml_accesssubtree WHERE docid like ? "
399
                + "AND controllevel like ?";
400

    
401

    
402
       try
403
       {
404
            pstmt = connection.prepareStatement(sql);
405
            // Increase DBConnection usage count
406
            connection.increaseUsageCount(1);
407
            // Bind the values to the query
408
            pstmt.setString(1, docid);
409
            pstmt.setString(2, TOPLEVEL);
410
            logMetacat.debug("Eml200SAXHandler.getTopAccessSubTreeFromDB - executing SQL: " + pstmt.toString());
411
            pstmt.execute();
412

    
413
            // Get result set
414
            rs = pstmt.getResultSet();
415
            if (rs.next())
416
            {
417
                String sectionId = rs.getString(1);
418
                long startNodeId = rs.getLong(2);
419
                long endNodeId = rs.getLong(3);
420
                // create a new access section
421
                topAccess = new AccessSection();
422
                topAccess.setControlLevel(TOPLEVEL);
423
                topAccess.setDocId(docid);
424
                topAccess.setSubTreeId(sectionId);
425
                topAccess.setStartNodeId(startNodeId);
426
                topAccess.setEndNodeId(endNodeId);
427
            }
428
            pstmt.close();
429
        }//try
430
        catch (SQLException e)
431
        {
432
            throw new SAXException(
433
                    "EMLSAXHandler.getTopAccessSubTreeFromDB(): "
434
                            + e.getMessage());
435
        }//catch
436
        finally
437
        {
438
            try
439
            {
440
                pstmt.close();
441
            }
442
            catch (SQLException ee)
443
            {
444
                throw new SAXException(
445
                        "EMLSAXHandler.getTopAccessSubTreeFromDB(): "
446
                                + ee.getMessage());
447
            }
448
        }//finally
449
        return topAccess;
450

    
451
     }
452

    
453
    /*
454
     * Get the subtree node info from xml_accesssubtree table
455
     */
456
    private Vector getAdditionalAccessSubTreeListFromDB() throws Exception
457
    {
458
        Vector result = new Vector();
459
        PreparedStatement pstmt = null;
460
        ResultSet rs = null;
461
        String sql = "SELECT subtreeid, startnodeid, endnodeid "
462
                + "FROM xml_accesssubtree WHERE docid like ? "
463
                + "AND controllevel like ? "
464
                + "ORDER BY startnodeid ASC";
465

    
466
        try
467
        {
468

    
469
            pstmt = connection.prepareStatement(sql);
470
            // Increase DBConnection usage count
471
            connection.increaseUsageCount(1);
472
            // Bind the values to the query
473
            pstmt.setString(1, docid);
474
            pstmt.setString(2, DATAACCESSLEVEL);
475
            pstmt.execute();
476

    
477
            // Get result set
478
            rs = pstmt.getResultSet();
479
            while (rs.next())
480
            {
481
                String sectionId = rs.getString(1);
482
                long startNodeId = rs.getLong(2);
483
                long endNodeId = rs.getLong(3);
484
                // create a new access section
485
                AccessSection accessObj = new AccessSection();
486
                accessObj.setControlLevel(DATAACCESSLEVEL);
487
                accessObj.setDocId(docid);
488
                accessObj.setSubTreeId(sectionId);
489
                accessObj.setStartNodeId(startNodeId);
490
                accessObj.setEndNodeId(endNodeId);
491
                // add this access obj into vector
492
                result.add(accessObj);
493

    
494
            }
495
            pstmt.close();
496
        }//try
497
        catch (SQLException e)
498
        {
499
            throw new SAXException(
500
                    "EMLSAXHandler.getadditionalAccessSubTreeListFromDB(): "
501
                            + e.getMessage());
502
        }//catch
503
        finally
504
        {
505
            try
506
            {
507
                pstmt.close();
508
            }
509
            catch (SQLException ee)
510
            {
511
                throw new SAXException(
512
                        "EMLSAXHandler.getAccessSubTreeListFromDB(): "
513
                                + ee.getMessage());
514
            }
515
        }//finally
516
        return result;
517
    }
518

    
519
   /*
520
    * Get the access subtree for referenced info from xml_accesssubtree table
521
    */
522
   private Hashtable getReferencedAccessSubTreeListFromDB() throws Exception
523
   {
524
       Hashtable result = new Hashtable();
525
       PreparedStatement pstmt = null;
526
       ResultSet rs = null;
527
       String sql = "SELECT subtreeid, startnodeid, endnodeid "
528
               + "FROM xml_accesssubtree WHERE docid like ? "
529
               + "AND controllevel like ? "
530
               + "ORDER BY startnodeid ASC";
531

    
532
       try
533
       {
534

    
535
           pstmt = connection.prepareStatement(sql);
536
           // Increase DBConnection usage count
537
           connection.increaseUsageCount(1);
538
           // Bind the values to the query
539
           pstmt.setString(1, docid);
540
           pstmt.setString(2, REFERENCEDLEVEL);
541
           pstmt.execute();
542

    
543
           // Get result set
544
           rs = pstmt.getResultSet();
545
           while (rs.next())
546
           {
547
               String sectionId = rs.getString(1);
548
               long startNodeId = rs.getLong(2);
549
               long endNodeId = rs.getLong(3);
550
               // create a new access section
551
               AccessSection accessObj = new AccessSection();
552
               accessObj.setControlLevel(DATAACCESSLEVEL);
553
               accessObj.setDocId(docid);
554
               accessObj.setSubTreeId(sectionId);
555
               accessObj.setStartNodeId(startNodeId);
556
               accessObj.setEndNodeId(endNodeId);
557
               // add this access obj into hastable
558
               if ( sectionId != null && !sectionId.trim().equals(""))
559
               {
560
                 result.put(sectionId, accessObj);
561
               }
562

    
563
           }
564
           pstmt.close();
565
       }//try
566
       catch (SQLException e)
567
       {
568
           throw new SAXException(
569
                   "EMLSAXHandler.getReferencedAccessSubTreeListFromDB(): "
570
                           + e.getMessage());
571
       }//catch
572
       finally
573
       {
574
           try
575
           {
576
               pstmt.close();
577
           }
578
           catch (SQLException ee)
579
           {
580
               throw new SAXException(
581
                       "EMLSAXHandler.getReferencedSubTreeListFromDB(): "
582
                               + ee.getMessage());
583
           }
584
       }//finally
585
       return result;
586
   }
587

    
588

    
589

    
590
    /** SAX Handler that is called at the start of each XML element */
591
    public void startElement(String uri, String localName, String qName,
592
            Attributes atts) throws SAXException
593
    {
594
        // for element <eml:eml...> qname is "eml:eml", local name is "eml"
595
        // for element <acl....> both qname and local name is "eml"
596
        // uri is namesapce
597
        logMetacat.debug("Start ELEMENT(qName) " + qName);
598
        logMetacat.debug("Start ELEMENT(localName) " + localName);
599
        logMetacat.debug("Start ELEMENT(uri) " + uri);
600

    
601
        DBSAXNode parentNode = null;
602
        DBSAXNode currentNode = null;
603
        // none inline part
604
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
605
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
606
        if (!handleInlineData)
607
        {
608
            // Get a reference to the parent node for the id
609
            try
610
            {
611
                parentNode = (DBSAXNode) nodeStack.peek();
612
            }
613
            catch (EmptyStackException e)
614
            {
615
                parentNode = null;
616
            }
617

    
618
            //start handle inline data
619
            //=====================================================
620
            if (qName.equals(INLINE) && !inAdditionalMetaData)
621
            {
622
                handleInlineData = true;
623
                inLineDataIndex++;
624
                //intitialize namespace hash for in line data
625
                inlineDataNameSpace = new Hashtable();
626
                //initialize file writer
627
                String docidWithoutRev = DocumentUtil.getDocIdFromString(docid);
628
                String seperator = ".";
629
                try {
630
					seperator = PropertyService.getProperty("document.accNumSeparator");
631
				} catch (PropertyNotFoundException pnfe) {
632
					logMetacat.error("Could not get property 'accNumSeparator'.  " 
633
							+ "Setting separator to '.': "+ pnfe.getMessage());
634
				}
635
                // the new file name will look like docid.rev.2
636
                inlineDataFileName = docidWithoutRev + seperator + revision
637
                        + seperator + inLineDataIndex;
638
                inlineDataFileWriter = createInlineDataFileWriter(inlineDataFileName, encoding);
639
                // put the inline file id into a vector. If upload failed,
640
                // metacat will
641
                // delete the inline data file
642
                inlineFileIDList.add(inlineDataFileName);
643

    
644
                // put distribution id and inline file id into a  hash
645
                if (distributionId != null)
646
                {
647
                  //check to see if this inline data is readable or writable to
648
                  // this user
649
                  if (!previousUnreadableInlineDataObjectHash.isEmpty() &&
650
                       previousUnreadableInlineDataObjectHash.containsKey(distributionId))
651
                  {
652
                      unReadableInlineDataObject = true;
653
                  }
654
                  if (!previousUnwritableInlineDataObjectHash.isEmpty() &&
655
                       previousUnwritableInlineDataObjectHash.containsKey(distributionId))
656
                  {
657
                     unWritableInlineDataObject = true;
658
                     numberOfHitUnWritableInlineData++;
659
                  }
660

    
661

    
662
                  // store the distributid and inlinedata filename into a hash
663
                  inlineDistributionIdList.put(distributionId, inlineDataFileName);
664
                }
665

    
666
            }
667
            //==============================================================
668

    
669

    
670
            // If hit a text node, we need write this text for current's parent
671
            // node
672
            // This will happend if the element is mixted
673
            //==============================================================
674
            if (hitTextNode && parentNode != null)
675
            {
676

    
677

    
678
                if (needToCheckAccessModule
679
                        && (processAdditionalAccess || processOtherAccess || processTopLevelAccess)) {
680
                    // stored the pull out nodes into storedNode stack
681
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
682
                            null, null, MetacatUtil.normalize(textBuffer
683
                                    .toString()));
684
                    storedAccessNodeStack.push(nodeElement);
685

    
686
                }
687

    
688
                // write the textbuffer into db for parent node.
689
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
690
                        parentNode);
691
                // rest hitTextNode
692
                hitTextNode = false;
693
                // reset textbuffer
694
                textBuffer = null;
695
                textBuffer = new StringBuffer();
696

    
697
            }
698
            //==================================================================
699

    
700
            // Document representation that points to the root document node
701
            //==================================================================
702
            if (atFirstElement)
703
            {
704
                atFirstElement = false;
705
                // If no DOCTYPE declaration: docname = root element
706
                // doctype = root element name or name space
707
                if (docname == null) {
708
                    docname = localName;
709
                    // if uri isn't null doctype = uri(namespace)
710
                    // othewise root element
711
                    if (uri != null && !(uri.trim()).equals("")) {
712
                        doctype = uri;
713
                    } else {
714
                        doctype = docname;
715
                    }
716
                    logMetacat.info("DOCNAME-a: " + docname);
717
                    logMetacat.info("DOCTYPE-a: " + doctype);
718
                } else if (doctype == null) {
719
                    // because docname is not null and it is declared in dtd
720
                    // so could not be in schema, no namespace
721
                    doctype = docname;
722
                    logMetacat.info("DOCTYPE-b: " + doctype);
723
                }
724
                rootNode.writeNodename(docname);
725
                //System.out.println("here!!!!!!!!!!!!!!!!!!1");
726
                try {
727
                    // for validated XML Documents store a reference to XML DB
728
                    // Catalog
729
                    // Because this is select statement and it needn't to roll
730
                    // back if
731
                    // insert document action fialed.
732
                    // In order to decrease DBConnection usage count, we get a
733
                    // new
734
                    // dbconnection from pool
735
                    //String catalogid = null;
736
                    DBConnection dbConn = null;
737
                    int serialNumber = -1;
738

    
739
                    try {
740
                        // Get dbconnection
741
                        dbConn = DBConnectionPool
742
                                .getDBConnection("DBSAXHandler.startElement");
743
                        serialNumber = dbConn.getCheckOutSerialNumber();
744

    
745
                        Statement stmt = dbConn.createStatement();
746
                        ResultSet rs = stmt
747
                                .executeQuery("SELECT catalog_id FROM xml_catalog "
748
                                        + "WHERE entry_type = 'Schema' "
749
                                        + "AND public_id = '" + doctype + "'");
750
                        boolean hasRow = rs.next();
751
                        if (hasRow) {
752
                            catalogid = rs.getString(1);
753
                        }
754
                        stmt.close();
755
                        //System.out.println("here!!!!!!!!!!!!!!!!!!2");
756
                    }//try
757
                    finally {
758
                        // Return dbconnection
759
                        DBConnectionPool.returnDBConnection(dbConn,
760
                                serialNumber);
761
                    }//finally
762

    
763
                    //create documentImpl object by the constructor which can
764
                    // specify
765
                    //the revision
766
                    if (!super.getIsRevisionDoc())
767
                    {
768
                       logMetacat.debug("EML200SaxHandler.startElement - creating new DocumentImple for " + docid);
769
                       currentDocument = new DocumentImpl(connection, rootNode
770
                            .getNodeID(), docname, doctype, docid, revision,
771
                            action, user, this.pub, catalogid, this.serverCode, 
772
                            createDate, updateDate);
773
                    }
774
                   
775

    
776
                } catch (Exception ane) {
777
                    throw (new SAXException("EML200SaxHandler.startElement - error with action " + 
778
                    		action + " : " + ane.getMessage()));
779
                }
780
                
781
            }
782
            //==================================================================
783

    
784
            // node
785
            //==================================================================
786
            // Create the current node representation
787
            currentNode = new DBSAXNode(connection, qName, localName,
788
                    parentNode, rootNode.getNodeID(), docid,
789
                    doctype);
790
            // Use a local variable to store the element node id
791
            // If this element is a start point of subtree(section), it will be
792
            // stored
793
            // otherwise, it will be discated
794
            long startNodeId = currentNode.getNodeID();
795
            // Add all of the namespaces
796
            String prefix = null;
797
            String nsuri = null;
798
            Enumeration prefixes = namespaces.keys();
799
            while (prefixes.hasMoreElements())
800
            {
801
                prefix = (String) prefixes.nextElement();
802
                nsuri = (String) namespaces.get(prefix);
803
                endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
804
            }
805

    
806
            //=================================================================
807
           // attributes
808
           // Add all of the attributes
809
          for (int i = 0; i < atts.getLength(); i++)
810
          {
811
              String attributeName = atts.getQName(i);
812
              String attributeValue = atts.getValue(i);
813
              endNodeId = currentNode.setAttribute(attributeName,
814
                      attributeValue, docid);
815

    
816
              // To handle name space and schema location if the attribute
817
              // name is
818
              // xsi:schemaLocation. If the name space is in not in catalog
819
              // table
820
              // it will be regeistered.
821
              if (attributeName != null
822
                      && attributeName
823
                              .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
824
                  SchemaLocationResolver resolver = new SchemaLocationResolver(
825
                          attributeValue);
826
                  resolver.resolveNameSpace();
827

    
828
              }
829
              else if (attributeName != null && attributeName.equals(ID) &&
830
                       currentNode.getTagName().equals(DISTRIBUTION) &&
831
                       !inAdditionalMetaData)
832
              {
833
                 // this is a distribution element and the id is distributionID
834
                 distributionId = attributeValue;
835
                 distributionAllIdList.put(distributionId, distributionId);
836

    
837
              }
838

    
839
          }//for
840

    
841

    
842
           //=================================================================
843

    
844
            // handle access stuff
845
            //==================================================================
846
            if (localName.equals(ACCESS))
847
            {
848
                //make sure the access is top level
849
                // this mean current node's parent's parent should be "eml"
850
                DBSAXNode tmpNode = (DBSAXNode) nodeStack.pop();// pop out
851
                                                                    // parent
852
                                                                    // node
853
                //peek out grandParentNode
854
                DBSAXNode grandParentNode = (DBSAXNode) nodeStack.peek();
855
                // put parent node back
856
                nodeStack.push(tmpNode);
857
                String grandParentTag = grandParentNode.getTagName();
858
                if (grandParentTag.equals(EML) && !inAdditionalMetaData)
859
                {
860
                  processTopLevelAccess = true;
861

    
862
                }
863
                else if ( !inAdditionalMetaData )
864
                {
865
                  // process other access embedded into resource level
866
                  // module
867
                  processOtherAccess = true;
868
                }
869
                else
870
                {
871
                  // this for access in additional data which doesn't have a
872
                  // described element. If it has a described element,
873
                  // this code won't hurt any thing
874
                  processAdditionalAccess = true;
875
                }
876

    
877

    
878
                // create access object
879
                accessObject = new AccessSection();
880
                // set permission order
881
                String permOrder = currentNode.getAttribute(ORDER);
882
                accessObject.setPermissionOrder(permOrder);
883
                // set access id
884
                String accessId = currentNode.getAttribute(ID);
885
                accessObject.setSubTreeId(accessId);
886
                // for additional access subtree, the  start of node id should
887
                // be describe element. We also stored the start access element
888
                // node id too.
889
                if (processAdditionalAccess)
890
                {
891
                  accessObject.setStartedDescribesNodeId(firstDescribesNodeId);
892
                  accessObject.setControlLevel(DATAACCESSLEVEL);
893
                }
894
                else if (processTopLevelAccess)
895
                {
896
                  accessObject.setControlLevel(TOPLEVEL);
897
                }
898
                else if (processOtherAccess)
899
                {
900
                  accessObject.setControlLevel(REFERENCEDLEVEL);
901
                }
902

    
903
                accessObject.setStartNodeId(startNodeId);
904
                accessObject.setDocId(docid);
905

    
906

    
907

    
908
            }
909
            // Set up a access rule for allow
910
            else if (parentNode.getTagName() != null
911
                    && (parentNode.getTagName()).equals(ACCESS)
912
                    && localName.equals(ALLOW))
913
           {
914

    
915
                accessRule = new AccessRule();
916

    
917
                //set permission type "allow"
918
                accessRule.setPermissionType(ALLOW);
919

    
920
            }
921
            // set up an access rule for den
922
            else if (parentNode.getTagName() != null
923
                    && (parentNode.getTagName()).equals(ACCESS)
924
                    && localName.equals(DENY))
925
           {
926
                accessRule = new AccessRule();
927
                //set permission type "allow"
928
                accessRule.setPermissionType(DENY);
929
            }
930

    
931
            //=================================================================
932
            // some other independ stuff
933

    
934
            // Add the node to the stack, so that any text data can be
935
            // added as it is encountered
936
            nodeStack.push(currentNode);
937
            // Add the node to the vector used by thread for writing XML Index
938
            nodeIndex.addElement(currentNode);
939

    
940
            // store access module element and attributes into stored stack
941
            if (needToCheckAccessModule
942
                    && (processAdditionalAccess || processOtherAccess || processTopLevelAccess))
943
            {
944
                // stored the pull out nodes into storedNode stack
945
                NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
946
                        localName, prefix, MetacatUtil.normalize(null));
947
                storedAccessNodeStack.push(nodeElement);
948
                for (int i = 0; i < atts.getLength(); i++) {
949
                    String attributeName = atts.getQName(i);
950
                    String attributeValue = atts.getValue(i);
951
                    NodeRecord nodeAttribute = new NodeRecord(-2, -2, -2,
952
                            "ATTRIBUTE", attributeName, null, MetacatUtil
953
                                    .normalize(attributeValue));
954
                    storedAccessNodeStack.push(nodeAttribute);
955
                }
956

    
957
            }
958

    
959
            if (currentNode.getTagName().equals(ADDITIONALMETADATA))
960
            {
961
              inAdditionalMetaData = true;
962
            }
963
            else if (currentNode.getTagName().equals(DESCRIBES) &&
964
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
965
                     firstDescribesInAdditionalMetadata)
966
            {
967
              // this is first decirbes element in additional metadata
968
              firstDescribesNodeId = startNodeId;
969
              // we started process additional access rules here
970
              // because access and describe couldn't be seperated
971
              NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
972
                        localName, prefix, MetacatUtil.normalize(null));
973
              storedAccessNodeStack.push(nodeElement);
974
              processAdditionalAccess = true;
975
              logMetacat.info("set processAdditonalAccess true when meet describe");
976
            }
977
            else if (inAdditionalMetaData && processAdditionalAccess &&
978
                     parentNode.getTagName().equals(ADDITIONALMETADATA) &&
979
                     !currentNode.getTagName().equals(DESCRIBES) &&
980
                     !currentNode.getTagName().equals(ACCESS))
981
            {
982
               // we start processadditionalAccess  module when first hit describes
983
               // in additionalMetadata. So this is possible, there are
984
               // "describes" but not "access". So here is try to terminate
985
               // processAddionalAccess. In this situation, there another element
986
               // rather than "describes" or "access" as a child of additionalMetadata
987
               // so this is impossible it will have access element now.
988
               // If additionalMetadata has access element, the flag will be
989
               // terminated in endElement
990
               processAdditionalAccess = false;
991
               logMetacat.warn("set processAddtionAccess false if the there is no access in additional");
992
            }
993
            else if (currentNode.getTagName().equals(DISTRIBUTION) &&
994
                     !inAdditionalMetaData)
995
            {
996
              proccessDistribution = true;
997
            }
998

    
999

    
1000
             //==================================================================
1001
            // reset name space
1002
            namespaces = null;
1003
            namespaces = new Hashtable();
1004

    
1005
        }//not inline data
1006
        // inline data
1007
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1008
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1009
        else
1010
        {
1011
            // we don't buffer the inline data in characters() method
1012
            // so start character don't need to hand text node.
1013

    
1014
            // inline data may be the xml format.
1015
            StringBuffer inlineElements = new StringBuffer();
1016
            inlineElements.append("<").append(qName);
1017
            // append attributes
1018
            for (int i = 0; i < atts.getLength(); i++) {
1019
                String attributeName = atts.getQName(i);
1020
                String attributeValue = atts.getValue(i);
1021
                inlineElements.append(" ");
1022
                inlineElements.append(attributeName);
1023
                inlineElements.append("=\"");
1024
                inlineElements.append(attributeValue);
1025
                inlineElements.append("\"");
1026
            }
1027
            // append namespace
1028
            String prefix = null;
1029
            String nsuri = null;
1030
            Enumeration prefixes = inlineDataNameSpace.keys();
1031
            while (prefixes.hasMoreElements()) {
1032
                prefix = (String) prefixes.nextElement();
1033
                nsuri =  (String)  inlineDataNameSpace.get(prefix);
1034
                inlineElements.append(" ");
1035
                inlineElements.append("xmlns:");
1036
                inlineElements.append(prefix);
1037
                inlineElements.append("=\"");
1038
                inlineElements.append(nsuri);
1039
                inlineElements.append("\"");
1040
            }
1041
            inlineElements.append(">");
1042
            //reset inline data name space
1043
            inlineDataNameSpace = null;
1044
            inlineDataNameSpace = new Hashtable();
1045
            //write inline data into file
1046
            logMetacat.info("the inline element data is: "
1047
                    + inlineElements.toString());
1048
            writeInlineDataIntoFile(inlineDataFileWriter, inlineElements);
1049
        }//else
1050
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1051
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1052

    
1053
    }
1054

    
1055

    
1056
    /** SAX Handler that is called for each XML text node */
1057
    public void characters(char[] cbuf, int start, int len) throws SAXException
1058
    {
1059
        logMetacat.info("CHARACTERS");
1060
        if (!handleInlineData) {
1061
            // buffer all text nodes for same element. This is for text was
1062
            // splited
1063
            // into different nodes
1064
            textBuffer.append(new String(cbuf, start, len));
1065
            // set hittextnode true
1066
            hitTextNode = true;
1067
            // if text buffer .size is greater than max, write it to db.
1068
            // so we can save memory
1069
            if (textBuffer.length() >= MAXDATACHARS)
1070
            {
1071
                logMetacat.info("Write text into DB in charaters"
1072
                           + " when text buffer size is greater than maxmum number");
1073
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1074
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1075
                        currentNode);
1076
                if (needToCheckAccessModule
1077
                     && (processAdditionalAccess || processOtherAccess || processTopLevelAccess))
1078
                {
1079
                     // stored the pull out nodes into storedNode stack
1080
                     NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1081
                       null, null, MetacatUtil.normalize(textBuffer
1082
                          .toString()));
1083
                     storedAccessNodeStack.push(nodeElement);
1084

    
1085
                }
1086
                textBuffer = null;
1087
                textBuffer = new StringBuffer();
1088
            }
1089
        }
1090
        else
1091
        {
1092
            // this is inline data and write file system directly
1093
            // we don't need to buffered it.
1094
            StringBuffer inlineText = new StringBuffer();
1095
            inlineText.append(new String(cbuf, start, len));
1096
            logMetacat.info(
1097
                    "The inline text data write into file system: "
1098
                            + inlineText.toString());
1099
            writeInlineDataIntoFile(inlineDataFileWriter, inlineText);
1100
        }
1101
    }
1102

    
1103
    /** SAX Handler that is called at the end of each XML element */
1104
    public void endElement(String uri, String localName, String qName)
1105
            throws SAXException
1106
    {
1107
        logMetacat.info("End ELEMENT " + qName);
1108

    
1109
        // when close inline element
1110
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1111
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1112
        if (localName.equals(INLINE) && handleInlineData)
1113
        {
1114
            // Get the node from the stack
1115
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1116
            String currentTag = currentNode.getTagName();
1117
            logMetacat.info("End of inline data");
1118
            // close file writer
1119
            try
1120
            {
1121
                inlineDataFileWriter.close();
1122
                handleInlineData = false;
1123
            }
1124
            catch (IOException ioe)
1125
            {
1126
                throw new SAXException(ioe.getMessage());
1127
            }
1128

    
1129
            //check if user changed inine data or not if user doesn't have
1130
            // write permission for this inline block
1131
            // if some error happends, we would delete the inline data file here,
1132
            // we will call a method named deletedInlineFiles in DocumentImple
1133
            if (unWritableInlineDataObject)
1134
            {
1135
                if (unReadableInlineDataObject)
1136
                {
1137
                  // now user just got a empty string in linline part
1138
                  // so if the user send back a empty string is fine and we will
1139
                  // copy the old file to new file. If he send something else,
1140
                  // the document will be rejected
1141
                  if (inlineDataIsEmpty(inlineDataFileName))
1142
                  {
1143
                    copyInlineFile(distributionId, inlineDataFileName);
1144
                  }
1145
                  else
1146
                  {
1147
                    logMetacat.info(
1148
                               "inline data was changed by a user"
1149
                                       + " who doesn't have permission");
1150
                    throw new SAXException(PERMISSIONERROR);
1151

    
1152
                  }
1153
                }//if
1154
                else
1155
                {
1156
                  // user get the inline data
1157
                  if (modifiedInlineData(distributionId, inlineDataFileName))
1158
                  {
1159
                    logMetacat.info(
1160
                                "inline data was changed by a user"
1161
                                        + " who doesn't have permission");
1162
                    throw new SAXException(PERMISSIONERROR);
1163
                  }//if
1164
                }//else
1165
            }//if
1166
            else
1167
            {
1168
               //now user can update file.
1169
               if (unReadableInlineDataObject)
1170
               {
1171
                  // now user just got a empty string in linline part
1172
                  // so if the user send back a empty string is fine and we will
1173
                  // copy the old file to new file. If he send something else,
1174
                  // the new inline data will overwite the old one(here we need
1175
                  // do nothing because the new inline data already existed
1176
                  if (inlineDataIsEmpty(inlineDataFileName))
1177
                  {
1178
                    copyInlineFile(distributionId, inlineDataFileName);
1179
                  }
1180
                }//if
1181

    
1182
            }//else
1183
            // put inline data file name into text buffer (without path)
1184
            textBuffer = new StringBuffer(inlineDataFileName);
1185
            // write file name into db
1186
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1187
                    currentNode);
1188
            // reset textbuff
1189
            textBuffer = null;
1190
            textBuffer = new StringBuffer();
1191
            // resetinlinedata file name
1192
            inlineDataFileName = null;
1193
            unWritableInlineDataObject = false;
1194
            unReadableInlineDataObject = false;
1195
            return;
1196
        }
1197
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1198
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1199

    
1200

    
1201

    
1202
        // close element which is not in inline data
1203
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1204
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1205
        if (!handleInlineData)
1206
        {
1207
            // Get the node from the stack
1208
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1209
            String currentTag = currentNode.getTagName();
1210

    
1211
            // If before the end element, the parser hit text nodes and store
1212
            // them
1213
            // into the buffer, write the buffer to data base. The reason we
1214
            // put
1215
            // write database here is for xerces some time split text node
1216
            if (hitTextNode)
1217
            {
1218
                // get access value
1219
                String data = null;
1220
                // add principal
1221
                if (currentTag.equals(PRINCIPAL) && accessRule != null)
1222
                {
1223
                    data = (textBuffer.toString()).trim();
1224
                    accessRule.addPrincipal(data);
1225

    
1226
                }
1227
                else if (currentTag.equals(PERMISSION) && accessRule != null)
1228
                {
1229
                    data = (textBuffer.toString()).trim();
1230
                    // we conbine different a permission into one value
1231
                    int permission = accessRule.getPermission();
1232
                    // add permision
1233
                    if (data.toUpperCase().equals(READSTRING))
1234
                    {
1235
                        permission = permission | READ;
1236
                    }
1237
                    else if (data.toUpperCase().equals(WRITESTRING))
1238
                    {
1239
                        permission = permission | WRITE;
1240
                    }
1241
                    else if (data.toUpperCase().equals(CHMODSTRING))
1242
                    {
1243
                        permission = permission | CHMOD;
1244
                    }
1245
                    else if (data.toUpperCase().equals(ALLSTRING))
1246
                    {
1247
                        permission = permission | ALL;
1248
                    }
1249
                    accessRule.setPermission(permission);
1250
                }
1251
                // put additionalmetadata/describes into vector
1252
                else if (currentTag.equals(DESCRIBES))
1253
                {
1254
                    data = (textBuffer.toString()).trim();
1255
                    describesId.add(data);
1256
                    //firstDescribesInAdditionalMetadata = false;
1257
                    //firstDescribesNodeId = 0;
1258
                }
1259
                else if (currentTag.equals(REFERENCES)
1260
                        && (processTopLevelAccess || processAdditionalAccess || processOtherAccess))
1261
                {
1262
                    // get reference
1263
                    data = (textBuffer.toString()).trim();
1264
                    // put reference id into accessSection
1265
                    accessObject.setReferences(data);
1266

    
1267
                }
1268
                else if (currentTag.equals(REFERENCES) && proccessDistribution)
1269
                {
1270
                  // get reference for distribution
1271
                  data = (textBuffer.toString()).trim();
1272
                  // we only stored the distribution reference which itself
1273
                  // has a id
1274
                  if (distributionId != null)
1275
                  {
1276
                    distributionReferenceList.put(distributionId, data);
1277
                  }
1278

    
1279
                }
1280
                else if (currentTag.equals(URL) && !inAdditionalMetaData)
1281
                {
1282
                    //handle online data, make sure its'parent is online
1283
                    DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1284
                    if (parentNode != null && parentNode.getTagName() != null
1285
                            && parentNode.getTagName().equals(ONLINE))
1286
                    {
1287
                        data = (textBuffer.toString()).trim();
1288
                        if (distributionId != null)
1289
                        {
1290
                          onlineURLDistributionIdList.put(distributionId, data);
1291
                        }
1292
                        else
1293
                        {
1294
                          onlineURLDistributionListWithoutId.add(data);
1295
                        }
1296
                    }//if
1297
                }//else if
1298
                // write text to db if it is not inline data
1299

    
1300
                logMetacat.info(
1301
                            "Write text into DB in End Element");
1302

    
1303
                 // write text node into db
1304
                 endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1305
                            currentNode);
1306

    
1307
                if (needToCheckAccessModule
1308
                        && (processAdditionalAccess || processOtherAccess || processTopLevelAccess)) {
1309
                    // stored the pull out nodes into storedNode stack
1310
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1311
                            null, null, MetacatUtil.normalize(textBuffer
1312
                                    .toString()));
1313
                    storedAccessNodeStack.push(nodeElement);
1314

    
1315
                }
1316
            }//if handle text node
1317

    
1318

    
1319

    
1320
            //set hitText false
1321
            hitTextNode = false;
1322
            // reset textbuff
1323
            textBuffer = null;
1324
            textBuffer = new StringBuffer();
1325

    
1326

    
1327
            // access stuff
1328
            if (currentTag.equals(ALLOW) || currentTag.equals(DENY))
1329
            {
1330
                // finish parser a ccess rule and assign it to new one
1331
                AccessRule newRule = accessRule;
1332
                //add the new rule to access section object
1333
                accessObject.addAccessRule(newRule);
1334
                // reset access rule
1335
                accessRule = null;
1336
            }// ALLOW or DENY
1337
            else if (currentTag.equals(ACCESS))
1338
            {
1339
                // finish parse a access setction and stored them into different
1340
                // places
1341

    
1342
                accessObject.setEndNodeId(endNodeId);
1343
                AccessSection newAccessObject = accessObject;
1344
                newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
1345
                if (newAccessObject != null)
1346
                {
1347

    
1348
                    if (processTopLevelAccess)
1349
                    {
1350
                       topAccessSection = newAccessObject;
1351

    
1352
                    }//if
1353
                    else if (processAdditionalAccess)
1354
                    {
1355
                        // for additional control
1356
                        // put discribesId into the accessobject and put this
1357
                        // access object into vector
1358
                        newAccessObject.setDescribedIdList(describesId);
1359
                        additionalAccessVector.add(newAccessObject);
1360

    
1361
                    }//if
1362
                    else if (processOtherAccess)
1363
                    {
1364
                      // we only stored the access object which has a id
1365
                      // because only the access object which has a id can
1366
                      // be reference
1367
                      if (newAccessObject.getSubTreeId() != null &&
1368
                          !newAccessObject.getSubTreeId().trim().equals(""))
1369
                      {
1370
                         possibleReferencedAccessHash.
1371
                           put(newAccessObject.getSubTreeId(), newAccessObject);
1372
                      }
1373
                    }
1374

    
1375
                }//if
1376
                //reset access section object
1377
                accessObject = null;
1378

    
1379
                // reset tmp stored node stack
1380
                storedAccessNodeStack = null;
1381
                storedAccessNodeStack = new Stack();
1382

    
1383
                // reset flag
1384
                processAdditionalAccess = false;
1385
                processTopLevelAccess = false;
1386
                processOtherAccess = false;
1387

    
1388
            }//access element
1389
            else if (currentTag.equals(ADDITIONALMETADATA))
1390
            {
1391
                //reset describesId
1392
                describesId = null;
1393
                describesId = new Vector();
1394
                inAdditionalMetaData = false;
1395
                firstDescribesNodeId = -1;
1396
                // reset tmp stored node stack
1397
                storedAccessNodeStack = null;
1398
                storedAccessNodeStack = new Stack();
1399

    
1400

    
1401
            }
1402
            else if (currentTag.equals(DISTRIBUTION) && !inAdditionalMetaData)
1403
            {
1404
               //reset distribution id
1405
               distributionId = null;
1406
               proccessDistribution = false;
1407
            }
1408
            else if (currentTag.equals(OFFLINE) && !inAdditionalMetaData)
1409
            {
1410
               if (distributionId != null)
1411
               {
1412
                 offlineDistributionIdList.put(distributionId, distributionId);
1413
               }
1414
            }
1415
            else if ((currentTag.equals(CONNECTION) || currentTag.equals(CONNECTIONDEFINITION))
1416
                     && !inAdditionalMetaData)
1417
            {
1418
              //handle online data, make sure its'parent is online
1419
                 DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1420
                 if (parentNode != null && parentNode.getTagName() != null
1421
                         && parentNode.getTagName().equals(ONLINE))
1422
                 {
1423
                     if (distributionId != null)
1424
                     {
1425
                        onlineOtherDistributionIdList.put(distributionId, distributionId);
1426
                     }
1427
                 }//if
1428

    
1429
            }//else if
1430
            else if (currentTag.equals(DESCRIBES))
1431
            {
1432
                firstDescribesInAdditionalMetadata = false;
1433

    
1434
            }
1435

    
1436

    
1437

    
1438
        }
1439
        // close elements which are in inline data (inline data can be xml doc)
1440
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1441
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1442
        else
1443
        {
1444
            // this is in inline part
1445
            StringBuffer endElement = new StringBuffer();
1446
            endElement.append("</");
1447
            endElement.append(qName);
1448
            endElement.append(">");
1449
            logMetacat.info("inline endElement: "
1450
                    + endElement.toString());
1451
            writeInlineDataIntoFile(inlineDataFileWriter, endElement);
1452
        }
1453
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1454
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1455
    }
1456

    
1457

    
1458
    /*
1459
     * Method to check if the new line data is as same as the old one
1460
     */
1461
     private boolean modifiedInlineData(String inlineDistributionId,
1462
			String newInlineInternalFileName) throws SAXException {
1463
       boolean modified = true;
1464
       if (inlineDistributionId == null || newInlineInternalFileName == null)
1465
       {
1466
         return modified;
1467
       }
1468
       String oldInlineInternalFileName =
1469
            (String)previousUnwritableInlineDataObjectHash.get(inlineDistributionId);
1470
       if (oldInlineInternalFileName == null ||
1471
           oldInlineInternalFileName.trim().equals(""))
1472
       {
1473
         return modified;
1474
       }
1475
       logMetacat.info("in handle inline data");
1476
       logMetacat.info("the inline data file name from xml_access is: "
1477
                                    + oldInlineInternalFileName);
1478

    
1479
       try
1480
       {
1481
         if (!compareInlineDataFiles(oldInlineInternalFileName,
1482
                                     newInlineInternalFileName))
1483
         {
1484
           modified = true;
1485

    
1486
         }
1487
         else
1488
         {
1489
           modified = false;
1490
         }
1491
       }
1492
       catch(Exception e)
1493
       {
1494
         modified = true;
1495
       }
1496

    
1497
       // delete the inline data file already in file system
1498
       if (modified)
1499
       {
1500
         deleteInlineDataFile(newInlineInternalFileName);
1501

    
1502
       }
1503
       return modified;
1504
     }
1505

    
1506
     /*
1507
      * A method to check if a line file is empty
1508
      */
1509
     private boolean inlineDataIsEmpty(String fileName) throws SAXException
1510
     {
1511
        boolean isEmpty = true;
1512
        if ( fileName == null)
1513
        {
1514
          throw new SAXException("The inline file name is null");
1515
        }
1516
        
1517
        try {
1518
			String path = PropertyService.getProperty("application.inlinedatafilepath");
1519
			// the new file name will look like path/docid.rev.2
1520
			File inlineDataDirectory = new File(path);
1521
			File inlineDataFile = new File(inlineDataDirectory, fileName);
1522

    
1523
			Reader inlineFileReader = new InputStreamReader(new FileInputStream(inlineDataFile), encoding);
1524
			BufferedReader inlineStringReader = new BufferedReader(inlineFileReader);
1525
			String string = inlineStringReader.readLine();
1526
			// at the end oldstring will be null
1527
			while (string != null) {
1528
				string = inlineStringReader.readLine();
1529
				if (string != null && !string.trim().equals("")) {
1530
					isEmpty = false;
1531
					break;
1532
				}
1533
			}
1534

    
1535
		} catch (Exception e) {
1536
			throw new SAXException(e.getMessage());
1537
		}
1538
		return isEmpty;
1539

    
1540
     }
1541

    
1542

    
1543
    /**
1544
	 * SAX Handler that receives notification of comments in the DTD
1545
	 */
1546
    public void comment(char[] ch, int start, int length) throws SAXException
1547
    {
1548
        logMetacat.info("COMMENT");
1549
        if (!handleInlineData) {
1550
            if (!processingDTD) {
1551
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1552
                String str = new String(ch, start, length);
1553

    
1554
                //compare comment if need
1555
                /*if (startCriticalSubTree) {
1556
                    compareCommentNode(currentUnChangedableSubtreeNodeStack,
1557
                            str, PERMISSIONERROR);
1558
                }//if*/
1559
                //compare top level access module
1560
                if (processTopLevelAccess && needToCheckAccessModule) {
1561
                    /*compareCommentNode(currentUnchangableAccessModuleNodeStack,
1562
                            str, UPDATEACCESSERROR);*/
1563
                }
1564
                endNodeId = currentNode.writeChildNodeToDB("COMMENT", null,
1565
                        str, docid);
1566
                if (needToCheckAccessModule
1567
                        && (processAdditionalAccess || processOtherAccess || processTopLevelAccess)) {
1568
                    // stored the pull out nodes into storedNode stack
1569
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2,
1570
                            "COMMENT", null, null, MetacatUtil.normalize(str));
1571
                    storedAccessNodeStack.push(nodeElement);
1572

    
1573
                }
1574
            }
1575
        } else {
1576
            // inline data comment
1577
            StringBuffer inlineComment = new StringBuffer();
1578
            inlineComment.append("<!--");
1579
            inlineComment.append(new String(ch, start, length));
1580
            inlineComment.append("-->");
1581
            logMetacat.info("inline data comment: "
1582
                    + inlineComment.toString());
1583
            writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1584
        }
1585
    }
1586

    
1587

    
1588

    
1589
    /**
1590
     * SAX Handler called once for each processing instruction found: node that
1591
     * PI may occur before or after the root element.
1592
     */
1593
    public void processingInstruction(String target, String data)
1594
            throws SAXException
1595
    {
1596
        logMetacat.info("PI");
1597
        if (!handleInlineData) {
1598
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1599
            endNodeId = currentNode.writeChildNodeToDB("PI", target, data,
1600
                    docid);
1601
        } else {
1602
            StringBuffer inlinePI = new StringBuffer();
1603
            inlinePI.append("<?");
1604
            inlinePI.append(target);
1605
            inlinePI.append(" ");
1606
            inlinePI.append(data);
1607
            inlinePI.append("?>");
1608
            logMetacat.info("inline data pi is: "
1609
                    + inlinePI.toString());
1610
            writeInlineDataIntoFile(inlineDataFileWriter, inlinePI);
1611
        }
1612
    }
1613

    
1614
    /** SAX Handler that is called at the start of Namespace */
1615
    public void startPrefixMapping(String prefix, String uri)
1616
            throws SAXException
1617
    {
1618
        logMetacat.info("NAMESPACE");
1619
        logMetacat.info("NAMESPACE prefix "+prefix);
1620
        logMetacat.info("NAMESPACE uri "+uri);
1621
        if (!handleInlineData) {
1622
            namespaces.put(prefix, uri);
1623
        } else {
1624
            inlineDataNameSpace.put(prefix, uri);
1625
        }
1626
    }
1627

    
1628
    /**
1629
     * SAX Handler that is called for each XML text node that is Ignorable
1630
     * white space
1631
     */
1632
    public void ignorableWhitespace(char[] cbuf, int start, int len)
1633
            throws SAXException
1634
    {
1635
        // When validation is turned "on", white spaces are reported here
1636
        // When validation is turned "off" white spaces are not reported here,
1637
        // but through characters() callback
1638
        logMetacat.info("IGNORABLEWHITESPACE");
1639
        if (!handleInlineData) {
1640
            DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1641
            String data = new String(cbuf, start, len);
1642

    
1643
                //compare whitespace in access top module
1644
                if (processTopLevelAccess && needToCheckAccessModule) {
1645
                    /*compareWhiteSpace(currentUnchangableAccessModuleNodeStack,
1646
                            data, UPDATEACCESSERROR);*/
1647
                }
1648
                // Write the content of the node to the database
1649
                if (needToCheckAccessModule
1650
                        && (processAdditionalAccess || processOtherAccess || processTopLevelAccess)) {
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
        } else {
1660
            //This is inline data write to file directly
1661
            StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf,
1662
                    start, len));
1663
            writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1664
        }
1665

    
1666
    }
1667

    
1668

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

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

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

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

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

    
1707

    
1708

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

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

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

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

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

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

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

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

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

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

    
1812

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

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

    
1832

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

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

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

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

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

    
1939

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

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

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

    
2023
   }//writeAdditonalLevelAccessRuletoDB
2024

    
2025

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

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

    
2065
         }
2066
       }//while
2067

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

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

    
2103
       try
2104
       {
2105

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

    
2120
           //Vector accessRules = accessSection.getAccessRules();
2121
           // go through every rule
2122
           for (int i = 0; i < accessRules.size(); i++)
2123
           {
2124
               AccessRule rule = (AccessRule) accessRules.elementAt(i);
2125
               String permType = rule.getPermissionType();
2126
               int permission = rule.getPermission();
2127
               pstmt.setInt(3, permission);
2128
               logMetacat.info("permission in accesstable: "
2129
                       + permission);
2130
               pstmt.setString(4, permType);
2131
               logMetacat.info(
2132
                       "Permtype in accesstable: " + permType);
2133
               // go through every principle in rule
2134
               Vector nameVector = rule.getPrincipal();
2135
               for (int j = 0; j < nameVector.size(); j++)
2136
               {
2137
                   String prName = (String) nameVector.elementAt(j);
2138
                   pstmt.setString(2, prName);
2139
                   logMetacat.info("Principal in accesstable: "
2140
                           + prName);
2141
                   logMetacat.debug("running sql: " + pstmt.toString());
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 additional 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
            logMetacat.debug("Eml200SAXHandler.writeAccessSubTreeIntoDB - executing SQL: " + pstmt.toString());
2325
            pstmt.execute();
2326
            pstmt.close();
2327
        }//try
2328
        catch (SQLException e)
2329
        {
2330
            throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2331
                    + e.getMessage());
2332
        }//catch
2333
        finally
2334
        {
2335
            try
2336
            {
2337
                pstmt.close();
2338
            }
2339
            catch (SQLException ee)
2340
            {
2341
                throw new SAXException(
2342
                        "EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2343
                                + ee.getMessage());
2344
            }
2345
        }//finally
2346

    
2347
    }//writeAccessSubtreeIntoDB
2348

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

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

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

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

    
2411

    
2412

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

    
2431
            Reader oldFileReader = new InputStreamReader(new FileInputStream(oldDataFile), encoding);
2432
            BufferedReader oldStringReader = new BufferedReader(oldFileReader);
2433
            Reader newFileReader = new InputStreamReader(new FileInputStream(newDataFile), encoding);
2434
            BufferedReader newStringReader = new BufferedReader(newFileReader);
2435
            // read first line of data
2436
            String oldString = oldStringReader.readLine();
2437
            String newString = newStringReader.readLine();
2438

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

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

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

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

    
2476
		if (oldInlineInternalFileName == null
2477
				|| oldInlineInternalFileName.trim().equals("")) {
2478
			throw new SAXException("Could not copy inline file from old one to new "
2479
					+ "one because can't find old file name");
2480
		}
2481
		logMetacat.info("in handle inline data");
2482
		logMetacat.info("the inline data file name from xml_access is: "
2483
				+ oldInlineInternalFileName);
2484

    
2485
		InputStream oldFileReader = null;
2486
		OutputStream newFileWriter = null;
2487
		try {
2488
			String path = PropertyService.getProperty("application.inlinedatafilepath");
2489
			// the new file name will look like path/docid.rev.2
2490
			File inlineDataDirectory = new File(path);
2491
			File oldDataFile = new File(inlineDataDirectory, oldInlineInternalFileName);
2492
			File newDataFile = new File(inlineDataDirectory, newFileName);
2493

    
2494
			oldFileReader = new FileInputStream(oldDataFile);
2495
			newFileWriter = new FileOutputStream(newDataFile);
2496
			byte[] buf = new byte[4 * 1024]; // 4K buffer
2497
			int b = oldFileReader.read(buf);
2498
			while (b != -1) {
2499
				newFileWriter.write(buf, 0, b);
2500
				b = oldFileReader.read(buf);
2501
			}
2502
		} catch (Exception e) {
2503
			throw new SAXException(e.getMessage());
2504
		} finally {
2505
			if (oldFileReader != null) {
2506
				try {
2507
					oldFileReader.close();
2508
				} catch (Exception ee) {
2509
					throw new SAXException(ee.getMessage());
2510
				}
2511

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

    
2520
			}
2521
		}
2522
	}
2523

    
2524

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

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

    
2551
    }
2552

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

    
2567
			fileReader = new InputStreamReader(new FileInputStream(dataFile), encoding);
2568
			// stringReader = new BufferedReader(fileReader);
2569
		} catch (Exception e) {
2570
			throw new McdbException(e.getMessage());
2571
		}
2572
		// return stringReader;
2573
		return fileReader;
2574
	}
2575

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

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

    
2643
    }//writeOnlineDataFileIdIntoRelationTable
2644

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

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

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

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

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

    
2777
        }//while
2778

    
2779
        //compare attributes
2780
        for (int i = 0; i < attributes.getLength(); i++) {
2781
            NodeRecord attriNode = null;
2782
            try {
2783
                attriNode = (NodeRecord) unchangableNodeStack.pop();
2784

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

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

    
2827
    }
2828

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

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

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

    
2927

    
2928

    
2929
}
(32-32/65)