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

    
28
package edu.ucsb.nceas.metacat;
29

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

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

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

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

    
115
    private boolean processOtherAccess = false;
116

    
117
    private AccessSection accessObject = null;
118

    
119
    private AccessRule accessRule = null;
120

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

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

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

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

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

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

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

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

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

    
164
    private boolean needCheckingAccessModule = false;
165

    
166
    private AccessSection unChangebleTopAccessSubTree = null;
167

    
168
    private Vector unChangebleAdditionalAccessSubTreeVector = new Vector();
169

    
170
    private Hashtable unChangebleReferencedAccessSubTreeHash = new Hashtable();
171

    
172
    private AccessSection topAccessSection;
173

    
174
    private Vector addtionalAccessVector = new Vector();
175

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

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

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

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

    
189
    private Hashtable inlineDataNameSpace = null;
190

    
191
    private FileWriter inlineDataFileWriter = null;
192

    
193
    private String inlineDataFileName = null;
194

    
195
    private int inLineDataIndex = 0;
196

    
197
    private Vector inlineFileIDList = new Vector();
198

    
199
    private boolean inAddtionalMetaData = false;
200

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

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

    
211
    private Hashtable previousUnreadableInlineDataObjectHash = new Hashtable();
212

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

    
219
    private Hashtable accessSubTreeAlreadyWriteDBList = new Hashtable();
220

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

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

    
239
    private int numberOfHitUnWritableInlineData = 0;
240

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
345
            }
346

    
347

    
348
        }
349
        catch (Exception e)
350
        {
351
            logMetacat.error("erorr in Eml200SAXHanlder is "
352
                                     +e.getMessage());
353
            throw new SAXException(e.getMessage());
354
        }
355
    }
356

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

    
371

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

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

    
420
     }
421

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

    
435
        try
436
        {
437

    
438
            pstmt = connection.prepareStatement(sql);
439
            // Increase DBConnection usage count
440
            connection.increaseUsageCount(1);
441
            // Bind the values to the query
442
            pstmt.setString(1, docid);
443
            pstmt.setString(2, DATAACCESSLEVEL);
444
            pstmt.execute();
445

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

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

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

    
501
       try
502
       {
503

    
504
           pstmt = connection.prepareStatement(sql);
505
           // Increase DBConnection usage count
506
           connection.increaseUsageCount(1);
507
           // Bind the values to the query
508
           pstmt.setString(1, docid);
509
           pstmt.setString(2, REFERENCEDLEVEL);
510
           pstmt.execute();
511

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

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

    
557

    
558

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

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

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

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

    
624

    
625
                  // store the distributid and inlinedata filename into a hash
626
                  inlineDistributionIdList.put(distributionId, inlineDataFileName);
627
                }
628

    
629
            }
630
            //==============================================================
631

    
632

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

    
640

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

    
649
                }
650

    
651
                // write the textbuffer into db for parent node.
652
                endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
653
                        parentNode);
654
                // rest hitTextNode
655
                hitTextNode = false;
656
                // reset textbuffer
657
                textBuffer = null;
658
                textBuffer = new StringBuffer();
659

    
660
            }
661
            //==================================================================
662

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

    
702
                    try {
703
                        // Get dbconnection
704
                        dbConn = DBConnectionPool
705
                                .getDBConnection("DBSAXHandler.startElement");
706
                        serialNumber = dbConn.getCheckOutSerialNumber();
707

    
708
                        Statement stmt = dbConn.createStatement();
709
                        ResultSet rs = stmt
710
                                .executeQuery("SELECT catalog_id FROM xml_catalog "
711
                                        + "WHERE entry_type = 'Schema' "
712
                                        + "AND public_id = '" + doctype + "'");
713
                        boolean hasRow = rs.next();
714
                        if (hasRow) {
715
                            catalogid = rs.getString(1);
716
                        }
717
                        stmt.close();
718
                        //System.out.println("here!!!!!!!!!!!!!!!!!!2");
719
                    }//try
720
                    finally {
721
                        // Return dbconnection
722
                        DBConnectionPool.returnDBConnection(dbConn,
723
                                serialNumber);
724
                    }//finally
725

    
726
                    //create documentImpl object by the constructor which can
727
                    // specify
728
                    //the revision
729
                    if (!super.getIsRevisionDoc())
730
                    {
731
                       
732
                       currentDocument = new DocumentImpl(connection, rootNode
733
                            .getNodeID(), docname, doctype, docid, revision,
734
                            action, user, this.pub, catalogid, this.serverCode, 
735
                            createDate, updateDate);
736
                    }
737
                   
738

    
739
                } catch (Exception ane) {
740
                    throw (new SAXException(
741
                            "Error in EMLSaxHandler.startElement " + action,
742
                            ane));
743
                }
744
                
745
            }
746
            //==================================================================
747

    
748
            // node
749
            //==================================================================
750
            // Create the current node representation
751
            currentNode = new DBSAXNode(connection, qName, localName,
752
                    parentNode, rootNode.getNodeID(), docid,
753
                    doctype);
754
            // Use a local variable to store the element node id
755
            // If this element is a start point of subtree(section), it will be
756
            // stored
757
            // otherwise, it will be discated
758
            long startNodeId = currentNode.getNodeID();
759
            // Add all of the namespaces
760
            String prefix = null;
761
            String nsuri = null;
762
            Enumeration prefixes = namespaces.keys();
763
            while (prefixes.hasMoreElements())
764
            {
765
                prefix = (String) prefixes.nextElement();
766
                nsuri = (String) namespaces.get(prefix);
767
                endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
768
            }
769

    
770
            //=================================================================
771
           // attributes
772
           // Add all of the attributes
773
          for (int i = 0; i < atts.getLength(); i++)
774
          {
775
              String attributeName = atts.getQName(i);
776
              String attributeValue = atts.getValue(i);
777
              endNodeId = currentNode.setAttribute(attributeName,
778
                      attributeValue, docid);
779

    
780
              // To handle name space and schema location if the attribute
781
              // name is
782
              // xsi:schemaLocation. If the name space is in not in catalog
783
              // table
784
              // it will be regeistered.
785
              if (attributeName != null
786
                      && attributeName
787
                              .indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
788
                  SchemaLocationResolver resolver = new SchemaLocationResolver(
789
                          attributeValue);
790
                  resolver.resolveNameSpace();
791

    
792
              }
793
              else if (attributeName != null && attributeName.equals(ID) &&
794
                       currentNode.getTagName().equals(DISTRIBUTION) &&
795
                       !inAddtionalMetaData)
796
              {
797
                 // this is a distribution element and the id is distributionID
798
                 distributionId = attributeValue;
799
                 distributionAllIdList.put(distributionId, distributionId);
800

    
801
              }
802

    
803
          }//for
804

    
805

    
806
           //=================================================================
807

    
808
            // handle access stuff
809
            //==================================================================
810
            if (localName.equals(ACCESS))
811
            {
812
                //make sure the access is top level
813
                // this mean current node's parent's parent should be "eml"
814
                DBSAXNode tmpNode = (DBSAXNode) nodeStack.pop();// pop out
815
                                                                    // parent
816
                                                                    // node
817
                //peek out grandParentNode
818
                DBSAXNode grandParentNode = (DBSAXNode) nodeStack.peek();
819
                // put parent node back
820
                nodeStack.push(tmpNode);
821
                String grandParentTag = grandParentNode.getTagName();
822
                if (grandParentTag.equals(EML) && !inAddtionalMetaData)
823
                {
824
                  processTopLeverAccess = true;
825

    
826
                }
827
                else if ( !inAddtionalMetaData )
828
                {
829
                  // process other access embedded into resource level
830
                  // module
831
                  processOtherAccess = true;
832
                }
833
                else
834
                {
835
                  // this for access in additional data which don't have
836
                  // described element. If it has a descirbed element,
837
                  // this code would hurt any thing
838
                  processAdditionalAccess = true;
839
                  logMetacat.warn("accessing process addtional access true when meet access");
840
                }
841

    
842

    
843
                // create access object
844
                accessObject = new AccessSection();
845
                // set permission order
846
                String permOrder = currentNode.getAttribute(ORDER);
847
                accessObject.setPermissionOrder(permOrder);
848
                // set access id
849
                String accessId = currentNode.getAttribute(ID);
850
                accessObject.setSubTreeId(accessId);
851
                // for additional access subtree, the  start of node id should
852
                // be describe element. We also stored the start access element
853
                // node id too.
854
                if (processAdditionalAccess)
855
                {
856
                  accessObject.seStartedDescribesNodeId(firstDescribesNodeId);
857
                  accessObject.setControlLevel(DATAACCESSLEVEL);
858
                }
859
                else if (processTopLeverAccess)
860
                {
861
                  accessObject.setControlLevel(TOPLEVEL);
862
                }
863
                else if (processOtherAccess)
864
                {
865
                  accessObject.setControlLevel(REFERENCEDLEVEL);
866
                }
867

    
868
                accessObject.setStartNodeId(startNodeId);
869
                accessObject.setDocId(docid);
870

    
871

    
872

    
873
            }
874
            // Set up a access rule for allow
875
            else if (parentNode.getTagName() != null
876
                    && (parentNode.getTagName()).equals(ACCESS)
877
                    && localName.equals(ALLOW))
878
           {
879

    
880
                accessRule = new AccessRule();
881

    
882
                //set permission type "allow"
883
                accessRule.setPermissionType(ALLOW);
884

    
885
            }
886
            // set up an access rule for den
887
            else if (parentNode.getTagName() != null
888
                    && (parentNode.getTagName()).equals(ACCESS)
889
                    && localName.equals(DENY))
890
           {
891
                accessRule = new AccessRule();
892
                //set permission type "allow"
893
                accessRule.setPermissionType(DENY);
894
            }
895

    
896
            //=================================================================
897
            // some other independ stuff
898

    
899
            // Add the node to the stack, so that any text data can be
900
            // added as it is encountered
901
            nodeStack.push(currentNode);
902
            // Add the node to the vector used by thread for writing XML Index
903
            nodeIndex.addElement(currentNode);
904

    
905
            // store access module element and attributes into stored stack
906
            if (needCheckingAccessModule
907
                    && (processAdditionalAccess || processOtherAccess || processTopLeverAccess))
908
            {
909
                // stored the pull out nodes into storedNode stack
910
                NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT",
911
                        localName, prefix, MetaCatUtil.normalize(null));
912
                storedAccessNodeStack.push(nodeElement);
913
                for (int i = 0; i < atts.getLength(); i++) {
914
                    String attributeName = atts.getQName(i);
915
                    String attributeValue = atts.getValue(i);
916
                    NodeRecord nodeAttribute = new NodeRecord(-2, -2, -2,
917
                            "ATTRIBUTE", attributeName, null, MetaCatUtil
918
                                    .normalize(attributeValue));
919
                    storedAccessNodeStack.push(nodeAttribute);
920
                }
921

    
922
            }
923

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

    
964

    
965
             //==================================================================
966
            // reset name space
967
            namespaces = null;
968
            namespaces = new Hashtable();
969

    
970
        }//not inline data
971
        // inline data
972
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
973
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
974
        else
975
        {
976
            // we don't buffer the inline data in characters() method
977
            // so start character don't need to hand text node.
978

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

    
1018
    }
1019

    
1020

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

    
1050
                }
1051
                textBuffer = null;
1052
                textBuffer = new StringBuffer();
1053
            }
1054
        }
1055
        else
1056
        {
1057
            // this is inline data and write file system directly
1058
            // we don't need to buffered it.
1059
            StringBuffer inlineText = new StringBuffer();
1060
            inlineText.append(new String(cbuf, start, len));
1061
            logMetacat.info(
1062
                    "The inline text data write into file system: "
1063
                            + inlineText.toString());
1064
            writeInlineDataIntoFile(inlineDataFileWriter, inlineText);
1065
        }
1066
    }
1067

    
1068
    /** SAX Handler that is called at the end of each XML element */
1069
    public void endElement(String uri, String localName, String qName)
1070
            throws SAXException
1071
    {
1072
        logMetacat.info("End ELEMENT " + qName);
1073

    
1074
        // when close inline element
1075
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1076
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1077
        if (localName.equals(INLINE) && handleInlineData)
1078
        {
1079
            // Get the node from the stack
1080
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1081
            String currentTag = currentNode.getTagName();
1082
            logMetacat.info("End of inline data");
1083
            // close file writer
1084
            try
1085
            {
1086
                inlineDataFileWriter.close();
1087
                handleInlineData = false;
1088
            }
1089
            catch (IOException ioe)
1090
            {
1091
                throw new SAXException(ioe.getMessage());
1092
            }
1093

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

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

    
1147
            }//else
1148
            // put inline data file name into text buffer (without path)
1149
            textBuffer = new StringBuffer(inlineDataFileName);
1150
            // write file name into db
1151
            endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1152
                    currentNode);
1153
            // reset textbuff
1154
            textBuffer = null;
1155
            textBuffer = new StringBuffer();
1156
            // resetinlinedata file name
1157
            inlineDataFileName = null;
1158
            unWritableInlineDataObject = false;
1159
            unReadableInlineDataObject = false;
1160
            return;
1161
        }
1162
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1163
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1164

    
1165

    
1166

    
1167
        // close element which is not in inline data
1168
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1169
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1170
        if (!handleInlineData)
1171
        {
1172
            // Get the node from the stack
1173
            DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
1174
            String currentTag = currentNode.getTagName();
1175

    
1176
            // If before the end element, the parser hit text nodes and store
1177
            // them
1178
            // into the buffer, write the buffer to data base. The reason we
1179
            // put
1180
            // write database here is for xerces some time split text node
1181
            if (hitTextNode)
1182
            {
1183
                // get access value
1184
                String data = null;
1185
                // add principal
1186
                if (currentTag.equals(PRINCIPAL) && accessRule != null)
1187
                {
1188
                    data = (textBuffer.toString()).trim();
1189
                    accessRule.addPrincipal(data);
1190

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

    
1232
                }
1233
                else if (currentTag.equals(REFERENCES) && proccessDistribution)
1234
                {
1235
                  // get reference for distribution
1236
                  data = (textBuffer.toString()).trim();
1237
                  // we only stored the distribution reference which itself
1238
                  // has a id
1239
                  if (distributionId != null)
1240
                  {
1241
                    distributionReferenceList.put(distributionId, data);
1242
                  }
1243

    
1244
                }
1245
                else if (currentTag.equals(URL) && !inAddtionalMetaData)
1246
                {
1247
                    //handle online data, make sure its'parent is online
1248
                    DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1249
                    if (parentNode != null && parentNode.getTagName() != null
1250
                            && parentNode.getTagName().equals(ONLINE))
1251
                    {
1252
                        data = (textBuffer.toString()).trim();
1253
                        if (distributionId != null)
1254
                        {
1255
                          onlineURLDistributionIdList.put(distributionId, data);
1256
                        }
1257
                        else
1258
                        {
1259
                          onelineURLDistributionListWithoutId.add(data);
1260
                        }
1261
                    }//if
1262
                }//else if
1263
                // write text to db if it is not inline data
1264

    
1265
                logMetacat.info(
1266
                            "Write text into DB in End Element");
1267

    
1268
                 // write text node into db
1269
                 endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer,
1270
                            currentNode);
1271

    
1272
                if (needCheckingAccessModule
1273
                        && (processAdditionalAccess || processOtherAccess || processTopLeverAccess)) {
1274
                    // stored the pull out nodes into storedNode stack
1275
                    NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT",
1276
                            null, null, MetaCatUtil.normalize(textBuffer
1277
                                    .toString()));
1278
                    storedAccessNodeStack.push(nodeElement);
1279

    
1280
                }
1281
            }//if handle text node
1282

    
1283

    
1284

    
1285
            //set hitText false
1286
            hitTextNode = false;
1287
            // reset textbuff
1288
            textBuffer = null;
1289
            textBuffer = new StringBuffer();
1290

    
1291

    
1292
            // access stuff
1293
            if (currentTag.equals(ALLOW) || currentTag.equals(DENY))
1294
            {
1295
                // finish parser a ccess rule and assign it to new one
1296
                AccessRule newRule = accessRule;
1297
                //add the new rule to access section object
1298
                accessObject.addAccessRule(newRule);
1299
                // reset access rule
1300
                accessRule = null;
1301
            }// ALLOW or DENY
1302
            else if (currentTag.equals(ACCESS))
1303
            {
1304
                // finish parse a access setction and stored them into different
1305
                // places
1306

    
1307
                accessObject.setEndNodeId(endNodeId);
1308
                AccessSection newAccessObject = accessObject;
1309
                newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
1310
                if (newAccessObject != null)
1311
                {
1312

    
1313
                    if (processTopLeverAccess)
1314
                    {
1315
                       topAccessSection = newAccessObject;
1316

    
1317
                    }//if
1318
                    else if (processAdditionalAccess)
1319
                    {
1320
                        // for additional control
1321
                        // put discribesId into the accessobject and put this
1322
                        // access object into vector
1323
                        newAccessObject.setDescribedIdList(describesId);
1324
                        addtionalAccessVector.add(newAccessObject);
1325

    
1326
                    }//if
1327
                    else if (processOtherAccess)
1328
                    {
1329
                      // we only stored the access object which has a id
1330
                      // because only the access object which has a id can
1331
                      // be reference
1332
                      if (newAccessObject.getSubTreeId() != null &&
1333
                          !newAccessObject.getSubTreeId().trim().equals(""))
1334
                      {
1335
                         possibleReferencedAccessHash.
1336
                           put(newAccessObject.getSubTreeId(), newAccessObject);
1337
                      }
1338
                    }
1339

    
1340
                }//if
1341
                //reset access section object
1342
                accessObject = null;
1343

    
1344
                // reset tmp stored node stack
1345
                storedAccessNodeStack = null;
1346
                storedAccessNodeStack = new Stack();
1347

    
1348
                // reset flag
1349
                processAdditionalAccess = false;
1350
                processTopLeverAccess = false;
1351
                processOtherAccess = false;
1352

    
1353
            }//access element
1354
            else if (currentTag.equals(ADDITIONALMETADATA))
1355
            {
1356
                //reset describesId
1357
                describesId = null;
1358
                describesId = new Vector();
1359
                inAddtionalMetaData = false;
1360
                firstDescribesNodeId = -1;
1361
                // reset tmp stored node stack
1362
                storedAccessNodeStack = null;
1363
                storedAccessNodeStack = new Stack();
1364

    
1365

    
1366
            }
1367
            else if (currentTag.equals(DISTRIBUTION) && !inAddtionalMetaData)
1368
            {
1369
               //reset distribution id
1370
               distributionId = null;
1371
               proccessDistribution = false;
1372
            }
1373
            else if (currentTag.equals(OFFLINE) && !inAddtionalMetaData)
1374
            {
1375
               if (distributionId != null)
1376
               {
1377
                 offlineDistributionIdList.put(distributionId, distributionId);
1378
               }
1379
            }
1380
            else if ((currentTag.equals(CONNECTION) || currentTag.equals(CONNECTIONDEFINITION))
1381
                     && !inAddtionalMetaData)
1382
            {
1383
              //handle online data, make sure its'parent is online
1384
                 DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
1385
                 if (parentNode != null && parentNode.getTagName() != null
1386
                         && parentNode.getTagName().equals(ONLINE))
1387
                 {
1388
                     if (distributionId != null)
1389
                     {
1390
                        onlineOtherDistributionIdList.put(distributionId, distributionId);
1391
                     }
1392
                 }//if
1393

    
1394
            }//else if
1395
            else if (currentTag.equals(DESCRIBES))
1396
            {
1397
                firstDescribesInAdditionalMetadata = false;
1398

    
1399
            }
1400

    
1401

    
1402

    
1403
        }
1404
        // close elements which are in inline data (inline data can be xml doc)
1405
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1406
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1407
        else
1408
        {
1409
            // this is in inline part
1410
            StringBuffer endElement = new StringBuffer();
1411
            endElement.append("</");
1412
            endElement.append(qName);
1413
            endElement.append(">");
1414
            logMetacat.info("inline endElement: "
1415
                    + endElement.toString());
1416
            writeInlineDataIntoFile(inlineDataFileWriter, endElement);
1417
        }
1418
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1419
        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1420
    }
1421

    
1422

    
1423
    /*
1424
     * Method to check if the new line data is as same as the old one
1425
     */
1426
     private boolean modifiedInlineData(String inlineDistributionId,
1427
                                          String newInlineInternalFileName)
1428
     {
1429
       boolean modified = true;
1430
       if (inlineDistributionId == null || newInlineInternalFileName == null)
1431
       {
1432
         return modified;
1433
       }
1434
       String oldInlineInternalFileName =
1435
            (String)previousUnwritableInlineDataObjectHash.get(inlineDistributionId);
1436
       if (oldInlineInternalFileName == null ||
1437
           oldInlineInternalFileName.trim().equals(""))
1438
       {
1439
         return modified;
1440
       }
1441
       logMetacat.info("in handle inline data");
1442
       logMetacat.info("the inline data file name from xml_access is: "
1443
                                    + oldInlineInternalFileName);
1444

    
1445
       try
1446
       {
1447
         if (!compareInlineDataFiles(oldInlineInternalFileName,
1448
                                     newInlineInternalFileName))
1449
         {
1450
           modified = true;
1451

    
1452
         }
1453
         else
1454
         {
1455
           modified = false;
1456
         }
1457
       }
1458
       catch(Exception e)
1459
       {
1460
         modified = true;
1461
       }
1462

    
1463
       // delete the inline data file already in file system
1464
       if (modified)
1465
       {
1466
         deleteInlineDataFile(newInlineInternalFileName);
1467

    
1468
       }
1469
       return modified;
1470
     }
1471

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

    
1502
        }
1503
        catch (Exception e)
1504
        {
1505
            throw new SAXException(e.getMessage());
1506
        }
1507
        return isEmpty;
1508

    
1509
     }
1510

    
1511

    
1512
    /**
1513
     * SAX Handler that receives notification of comments in the DTD
1514
     */
1515
    public void comment(char[] ch, int start, int length) throws SAXException
1516
    {
1517
        logMetacat.info("COMMENT");
1518
        if (!handleInlineData) {
1519
            if (!processingDTD) {
1520
                DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1521
                String str = new String(ch, start, length);
1522

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

    
1542
                }
1543
            }
1544
        } else {
1545
            // inline data comment
1546
            StringBuffer inlineComment = new StringBuffer();
1547
            inlineComment.append("<!--");
1548
            inlineComment.append(new String(ch, start, length));
1549
            inlineComment.append("-->");
1550
            logMetacat.info("inline data comment: "
1551
                    + inlineComment.toString());
1552
            writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1553
        }
1554
    }
1555

    
1556

    
1557

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

    
1583
    /** SAX Handler that is called at the start of Namespace */
1584
    public void startPrefixMapping(String prefix, String uri)
1585
            throws SAXException
1586
    {
1587
        logMetacat.info("NAMESPACE");
1588
        logMetacat.info("NAMESPACE prefix "+prefix);
1589
        logMetacat.info("NAMESPACE uri "+uri);
1590
        if (!handleInlineData) {
1591
            namespaces.put(prefix, uri);
1592
        } else {
1593
            inlineDataNameSpace.put(prefix, uri);
1594
        }
1595
    }
1596

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

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

    
1630
                //compare whitespace if need
1631
                /*if (startCriticalSubTree) {
1632
                    compareWhiteSpace(currentUnChangedableSubtreeNodeStack,
1633
                            data, PERMISSIONERROR);
1634
                }//if*/
1635

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

    
1649
                }
1650
                endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data,
1651
                        docid);
1652
            }
1653
        } else {
1654
            //This is inline data write to file directly
1655
            StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf,
1656
                    start, len));
1657
            writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1658
        }
1659

    
1660
    }
1661

    
1662

    
1663
    /** SAX Handler that receives notification of end of the document */
1664
    public void endDocument() throws SAXException
1665
    {
1666
        logMetacat.info("end Document");
1667
        if (needCheckingAccessModule)
1668
        {
1669
          compareAllAccessModules();
1670
        }
1671

    
1672
        // user deleted some inline block which it counldn't delete
1673
        if (numberOfHitUnWritableInlineData !=
1674
            previousUnwritableInlineDataObjectHash.size())
1675
        {
1676
          throw new SAXException("user deleted some inline block it couldn't");
1677
        }
1678

    
1679
        if (!super.getIsRevisionDoc())
1680
        {
1681
          // write access rule to xml_access table which include both top level
1682
          // and additional level(data access level). It also write access subtree
1683
          // info into xml_accesssubtree about the top access, additional access
1684
          // and some third place access modules which are referenced by top
1685
          // level or additional level
1686
          writeAccessRuleToDB();
1687

    
1688
          //delete relation table
1689
          deleteRelations();
1690
          //write relations
1691
           for (int i = 0; i < onlineDataFileIdInRelationVector.size(); i++) {
1692
            String id = (String) onlineDataFileIdInRelationVector.elementAt(i);
1693
            writeOnlineDataFileIdIntoRelationTable(id);
1694
           }
1695
        }
1696

    
1697
        // clean the subtree record
1698
        accessSubTreeAlreadyWriteDBList = new Hashtable();
1699
    }
1700

    
1701

    
1702

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

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

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

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

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

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

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

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

    
1796
      // now stack1 is empty and we should make sure stack2 is empty too
1797
      if (!stack2.isEmpty()) {
1798

    
1799
          logMetacat.info(
1800
                  "stack2 still have some elements while stack1 "
1801
                          + "is empty! ");
1802
          throw new SAXException(UPDATEACCESSERROR);
1803
      }//if
1804
  }//comparingNodeStacks
1805

    
1806

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

    
1820
        if (topAccessSection != null){
1821
          writeTopLevelAccessRuleToDB();
1822
        }
1823
        //System.out.println("after write top access rules");
1824
    }//writeAccessRuleToDB
1825

    
1826

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

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

    
1879
           // search possible referenced access hashtable
1880
           if (possibleReferencedAccessHash.containsKey(reference))
1881
           {
1882
             AccessSection referenceAccess = (AccessSection)
1883
                         possibleReferencedAccessHash.get(reference);
1884
             return resolveAccessRuleReference(referenceAccess);
1885
           }
1886

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

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

    
1933

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

    
1959
       if (describeIdList == null || describeIdList.isEmpty())
1960
       {
1961
         continue;
1962
       }
1963

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

    
2017
   }//writeAdditonalLevelAccessRuletoDB
2018

    
2019

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

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

    
2059
         }
2060
       }//while
2061

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

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

    
2097
       try
2098
       {
2099

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

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

    
2158
    }//writeGivenAccessRuleIntoDB
2159

    
2160

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

    
2174
        } catch (SQLException e) {
2175
            throw new SAXException(e.getMessage());
2176
        } finally {
2177
            try {
2178
                stmt.close();
2179
            } catch (SQLException ee) {
2180
                throw new SAXException(ee.getMessage());
2181
            }
2182
        }
2183
    }//deletePermissionsInAccessTable
2184

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

    
2213
    }
2214

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

    
2242
    }
2243

    
2244
    /*
2245
     * In order to make sure only usr has "all" permission can update access
2246
     * subtree in eml document we need to keep access subtree info in
2247
     * xml_accesssubtree table, such as docid, version, startnodeid, endnodeid
2248
     */
2249
    private void writeAccessSubTreeIntoDB(AccessSection accessSection)
2250
                                          throws SAXException
2251
    {
2252
        if (accessSection == null)
2253
        {
2254

    
2255
          logMetacat.info("Access object is null and tried to write "+
2256
                                   "into access subtree table");
2257
          throw new SAXException("The access object is null to write access " +
2258
                                 "sbutree");
2259
        }
2260

    
2261
        String sql = null;
2262
        PreparedStatement pstmt = null;
2263
        sql = "INSERT INTO xml_accesssubtree (docid, rev, controllevel, "
2264
                + "subtreeid, startnodeid, endnodeid) VALUES "
2265
                + " (?, ?, ?, ?, ?, ?)";
2266
        try
2267
        {
2268

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

    
2292
            long endNodeId = accessSection.getEndNodeId();
2293
            String sectionId = accessSection.getSubTreeId();
2294

    
2295
            if (startNodeId ==-1 || endNodeId == -1)
2296
            {
2297
              throw new SAXException("Don't find start node or end node id " +
2298
                                      "for the access subtee");
2299

    
2300
            }
2301

    
2302
            // Bind the values to the query
2303
            pstmt.setString(1, docid);
2304
            logMetacat.info("Docid in access-subtreetable: " + docid);
2305
            pstmt.setInt(2, (new Integer(revision)).intValue());
2306
            logMetacat.info("rev in accesssubtreetable: " + revision);
2307
            pstmt.setString(3, level);
2308
            logMetacat.info("contorl level in access-subtree table: "
2309
                    + level);
2310
            pstmt.setString(4, sectionId);
2311
            logMetacat.info("Subtree id in access-subtree table: "
2312
                    + sectionId);
2313
            pstmt.setLong(5, startNodeId);
2314
            logMetacat.info("Start node id is: " + startNodeId);
2315
            pstmt.setLong(6, endNodeId);
2316
            logMetacat.info("End node id is: " + endNodeId);
2317
            pstmt.execute();
2318
            pstmt.close();
2319
        }//try
2320
        catch (SQLException e)
2321
        {
2322
            throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2323
                    + e.getMessage());
2324
        }//catch
2325
        finally
2326
        {
2327
            try
2328
            {
2329
                pstmt.close();
2330
            }
2331
            catch (SQLException ee)
2332
            {
2333
                throw new SAXException(
2334
                        "EMLSAXHandler.writeAccessSubTreeIntoDB(): "
2335
                                + ee.getMessage());
2336
            }
2337
        }//finally
2338

    
2339
    }//writeAccessSubtreeIntoDB
2340

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

    
2353
        } catch (SQLException e) {
2354
            throw new SAXException(e.getMessage());
2355
        } finally {
2356
            try {
2357
                stmt.close();
2358
            } catch (SQLException ee) {
2359
                throw new SAXException(ee.getMessage());
2360
            }
2361
        }
2362
    }//deleteAccessSubTreeRecord
2363

    
2364
    // open a file writer for writing inline data to file
2365
    private FileWriter createInlineDataFileWriter(String fileName)
2366
            throws SAXException
2367
    {
2368
        FileWriter writer = null;
2369
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2370
        /*
2371
         * File inlineDataDirectory = new File(path);
2372
         */
2373
        String newFile = path + "/" + fileName;
2374
        logMetacat.info("inline file name: " + newFile);
2375
        try {
2376
            // true means append
2377
            writer = new FileWriter(newFile, true);
2378
        } catch (IOException ioe) {
2379
            throw new SAXException(ioe.getMessage());
2380
        }
2381
        return writer;
2382
    }
2383

    
2384
    // write inline data into file system and return file name(without path)
2385
    private void writeInlineDataIntoFile(FileWriter writer, StringBuffer data)
2386
            throws SAXException
2387
    {
2388
        try {
2389
            writer.write(data.toString());
2390
            writer.flush();
2391
        } catch (Exception e) {
2392
            throw new SAXException(e.getMessage());
2393
        }
2394
    }
2395

    
2396

    
2397

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

    
2423
            // at the end oldstring will be null
2424
            while (oldString != null) {
2425
                oldString = oldStringReader.readLine();
2426
                newString = newStringReader.readLine();
2427
                if (!oldString.equals(newString)) {
2428
                    same = false;
2429
                    break;
2430
                }
2431
            }
2432

    
2433
            // if oldString is null but newString is not null, they are same
2434
            if (same) {
2435
                if (newString != null) {
2436
                    same = false;
2437
                }
2438
            }
2439

    
2440
        } catch (Exception e) {
2441
            throw new McdbException(e.getMessage());
2442
        }
2443
        logMetacat.info("the inline data retrieve from file: " + data);
2444
        return same;
2445
    }
2446

    
2447
   /*
2448
    * Copy a old line file to a new inline file
2449
    */
2450
   public void copyInlineFile(String inlineDistributionId, String newFileName)
2451
           throws SAXException
2452
   {
2453
     if (inlineDistributionId == null || newFileName == null)
2454
     {
2455
       throw new SAXException("Could not copy inline file from old one to new "+
2456
                              "one!");
2457
     }
2458
     // get old file id from previousUnreadable data object
2459
    String oldInlineInternalFileName =
2460
         (String)previousUnreadableInlineDataObjectHash.get(inlineDistributionId);
2461

    
2462
    if (oldInlineInternalFileName == null ||
2463
        oldInlineInternalFileName.trim().equals(""))
2464
    {
2465
      throw new SAXException("Could not copy inline file from old one to new "+
2466
                              "one because can't find old file name");
2467
    }
2468
    logMetacat.info("in handle inline data");
2469
    logMetacat.info("the inline data file name from xml_access is: "
2470
                                 + oldInlineInternalFileName);
2471

    
2472
    String path = MetaCatUtil.getOption("inlinedatafilepath");
2473
    // the new file name will look like path/docid.rev.2
2474
    File inlineDataDirectory = new File(path);
2475
    File oldDataFile = new File(inlineDataDirectory, oldInlineInternalFileName);
2476
    File newDataFile = new File(inlineDataDirectory, newFileName);
2477
    FileReader oldFileReader = null;
2478
    FileWriter newFileWriter = null;
2479
    try
2480
    {
2481
      oldFileReader = new FileReader(oldDataFile);
2482
      newFileWriter = new FileWriter(newDataFile);
2483
      char[] buf = new char[4 * 1024]; // 4K buffer
2484
      int b = oldFileReader.read(buf);
2485
      while (b != -1)
2486
      {
2487
        newFileWriter.write(buf, 0, b);
2488
        b = oldFileReader.read(buf);
2489

    
2490
      }
2491
    }
2492
    catch (Exception e)
2493
    {
2494
      throw new SAXException(e.getMessage());
2495
    }
2496
    finally
2497
    {
2498
        if (oldFileReader != null)
2499
        {
2500
          try
2501
          {
2502
            oldFileReader.close();
2503
          }
2504
          catch (Exception ee)
2505
          {
2506
            throw new SAXException(ee.getMessage());
2507
          }
2508

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

    
2521
        }
2522

    
2523
    }
2524

    
2525
  }
2526

    
2527

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

    
2540
    /* delete the inline data file */
2541
    private void deleteInlineDataFile(String fileName)
2542
    {
2543

    
2544
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2545
        File inlineDataDirectory = new File(path);
2546
        File newFile = new File(inlineDataDirectory, fileName);
2547
        newFile.delete();
2548

    
2549
    }
2550

    
2551
    /*
2552
     * In eml2, the inline data wouldn't store in db, it store in file system
2553
     * The db stores file name(without path).
2554
     */
2555
    public static Reader readInlineDataFromFileSystem(String fileName)
2556
            throws McdbException
2557
    {
2558
        //BufferedReader stringReader = null;
2559
        FileReader fileReader = null;
2560
        String path = MetaCatUtil.getOption("inlinedatafilepath");
2561
        // the new file name will look like path/docid.rev.2
2562
        File inlineDataDirectory = new File(path);
2563
        File dataFile = new File(inlineDataDirectory, fileName);
2564
        try {
2565
            fileReader = new FileReader(dataFile);
2566
            //stringReader = new BufferedReader(fileReader);
2567
        } catch (Exception e) {
2568
            throw new McdbException(e.getMessage());
2569
        }
2570
        // return stringReader;
2571
        return fileReader;
2572
    }
2573

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

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

    
2639
    }//writeOnlineDataFileIdIntoRelationTable
2640

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

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

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

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

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

    
2773
        }//while
2774

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

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

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

    
2823
    }
2824

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

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

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

    
2923

    
2924

    
2925
}
(34-34/66)