Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that handles the SAX XML events as they
4
 *             are generated from XML documents
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Matt Jones, Jivka Bojilova
8
 *    Release: @release@
9
 *
10
 *   '$Author: tao $'
11
 *     '$Date: 2003-03-05 18:42:07 -0800 (Wed, 05 Mar 2003) $'
12
 * '$Revision: 1459 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.sql.*;
32
import java.io.File;
33
import java.io.FileWriter;
34
import java.io.StringReader;
35
import java.util.Stack;
36
import java.util.Vector;
37
import java.util.Hashtable;
38
import java.util.Enumeration;
39
import java.util.EmptyStackException;
40

    
41
import org.xml.sax.Attributes;
42
import org.xml.sax.SAXException;
43
import org.xml.sax.SAXParseException;
44
import org.xml.sax.ext.DeclHandler;
45
import org.xml.sax.ext.LexicalHandler;
46
import org.xml.sax.helpers.DefaultHandler;
47

    
48
/**
49
 * A database aware Class implementing callback bethods for the SAX parser to
50
 * call when processing the XML stream and generating events
51
 */
52
public class EmlSAXHandler extends DBSAXHandler implements 
53
                                                      AccessControlInterface
54
{
55
   private Vector allowRules = new Vector();
56
   private Vector denyRules = new Vector();
57
   private String documentId = null;
58
   private Vector subDocumentIdList = new Vector();
59
   private boolean processTopLeverAccess = false;
60
   private boolean processAdditionalAccess = false;
61
   private AccessSection accessObject= null;
62
   private AccessRule accessRule = null;
63
   private Vector accessObjectList = new Vector(); // store every access rule
64
   private Hashtable topLevelAccessControlMap = new Hashtable();
65
   private Hashtable additionalAccessControlMap = new Hashtable();
66
   private Vector describesId = new Vector(); // store the ids in
67
                                      //additionalmetadata/describes
68
   private Stack subTreeInfoStack = new Stack();
69
   private Vector subTreeList = new Vector();// store the final subtree
70
   private int inLineDataIndex = 1;
71
 
72
 
73
   // Constant
74
   private static final String DESCRIBES = "describes";
75
   private static final String ADDITIONALMETADATA = "additionalMetadata";
76
   private static final String ORDER = "order";
77
   private static final String ID ="id";
78
   private static final String REFERENCES = "references";
79
   public  static final String INLINE = "inline";
80
      
81
  
82
    /** Construct an instance of the handler class
83
    * In this constructor, user can specify the version need to upadate
84
    *
85
    * @param conn the JDBC connection to which information is written
86
    * @param action - "INSERT" or "UPDATE"
87
    * @param docid to be inserted or updated into JDBC connection
88
    * @param revision, the user specified the revision need to be update
89
    * @param user the user connected to MetaCat servlet and owns the document
90
    * @param groups the groups to which user belongs
91
    * @param pub flag for public "read" access on document
92
    * @param serverCode the serverid from xml_replication on which this document
93
    *        resides.
94
    *
95
    */
96
   public EmlSAXHandler(DBConnection conn, String action, String docid,
97
     String revision, String user, String[] groups, String pub, int serverCode)
98
   {
99
     super(conn, action, docid, revision, user, groups, pub, serverCode);
100
   }
101
   
102
   /** SAX Handler that is called at the start of each XML element */
103
   public void startElement(String uri, String localName,
104
                            String qName, Attributes atts)
105
               throws SAXException 
106
  {
107
      // for element <eml:eml...> qname is "eml:eml", local name is "eml"            
108
     // for element <acl....> both qname and local name is "eml"
109
     // uri is namesapce
110
     MetaCatUtil.debugMessage("Start ELEMENT(qName) " + qName, 50);
111
     MetaCatUtil.debugMessage("Start ELEMENT(localName) " + localName, 50);
112
     MetaCatUtil.debugMessage("Start ELEMENT(uri) " + uri, 50);
113
     
114
     
115
     DBSAXNode parentNode = null;
116
     DBSAXNode currentNode = null;
117

    
118
     // Get a reference to the parent node for the id
119
     try 
120
     {
121
       parentNode = (DBSAXNode)nodeStack.peek();
122
     } 
123
     catch (EmptyStackException e) 
124
     {
125
       parentNode = null;
126
     }
127
     
128
     // If hit a text node, we need write this text for current's parent node
129
     // This will happend if the element is mixted
130
     if (hitTextNode && parentNode != null)
131
     {
132
       // write the textbuffer into db for parent node.
133
        endNodeId = writeTextForDBSAXNode(textBuffer, parentNode);
134
        // rest hitTextNode
135
        hitTextNode =false;
136
        // reset textbuffer
137
        textBuffer = null;
138
        textBuffer = new StringBuffer();
139
       
140
     }
141
     
142
  
143
     // Document representation that points to the root document node
144
     if (atFirstElement) 
145
     {
146
       atFirstElement = false;
147
       // If no DOCTYPE declaration: docname = root element
148
       // doctype = root element name or name space
149
       if (docname == null) 
150
       {
151
         docname = localName;
152
         // if uri isn't null doctype = uri(namespace)
153
         // othewise root element
154
         if (uri != null && !(uri.trim()).equals(""))
155
         {
156
           doctype = uri;
157
         }
158
         else
159
         {
160
           doctype = docname;
161
         }
162
         MetaCatUtil.debugMessage("DOCNAME-a: " + docname, 30);
163
         MetaCatUtil.debugMessage("DOCTYPE-a: " + doctype, 30);
164
       } 
165
       else if (doctype == null) 
166
       {
167
         // because docname is not null and it is declared in dtd
168
         // so could not be in schema, no namespace
169
         doctype = docname;
170
         MetaCatUtil.debugMessage("DOCTYPE-b: " + doctype, 30);
171
       }
172
       rootNode.writeNodename(docname);
173
       try 
174
       {
175
         // for validated XML Documents store a reference to XML DB Catalog
176
         // Because this is select statement and it needn't to roll back if
177
         // insert document action fialed.
178
         // In order to decrease DBConnection usage count, we get a new
179
         // dbconnection from pool
180
         String catalogid = null;
181
         DBConnection dbConn = null;
182
         int serialNumber = -1;
183

    
184
         if ( systemid != null ) 
185
         {
186
           try
187
           {
188
            // Get dbconnection
189
            dbConn=DBConnectionPool.getDBConnection
190
                                          ("DBSAXHandler.startElement");
191
            serialNumber=dbConn.getCheckOutSerialNumber();
192

    
193
            Statement stmt = dbConn.createStatement();
194
            ResultSet rs = stmt.executeQuery(
195
                          "SELECT catalog_id FROM xml_catalog " +
196
                          "WHERE entry_type = 'DTD' " +
197
                          "AND public_id = '" + doctype + "'");
198
            boolean hasRow = rs.next();
199
            if ( hasRow ) {
200
              catalogid = rs.getString(1);
201
            }
202
            stmt.close();
203
           }//try
204
           finally
205
           {
206
             // Return dbconnection
207
             DBConnectionPool.returnDBConnection(dbConn, serialNumber);
208
           }//finally
209
         }
210

    
211
         //create documentImpl object by the constructor which can specify
212
         //the revision
213
         currentDocument = new DocumentImpl(connection, rootNode.getNodeID(),
214
                               docname, doctype, docid, revision, action, user,
215
                               this.pub, catalogid, this.serverCode);
216

    
217

    
218
       } 
219
       catch (Exception ane) 
220
       {
221
         throw (new SAXException("Error in DBSaxHandler.startElement " +
222
                                 action, ane));
223
       }
224
     }
225

    
226
     // Create the current node representation
227
     currentNode = new DBSAXNode(connection, qName, localName, parentNode,
228
                                 currentDocument.getRootNodeID(),docid,
229
                                 currentDocument.getDoctype());
230
     // Use a local variable to store the element node id
231
     // If this element is a start point of subtree(section), it will be stored
232
     // otherwise, it will be discated
233
     long startNodeId = currentNode.getNodeID();
234
     // Add all of the namespaces
235
     String prefix;
236
     String nsuri;
237
     Enumeration prefixes = namespaces.keys();
238
     while ( prefixes.hasMoreElements() ) 
239
     {
240
       prefix = (String)prefixes.nextElement();
241
       nsuri = (String)namespaces.get(prefix);
242
       endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
243
     }
244
     namespaces = null;
245
     namespaces = new Hashtable();
246

    
247
     // Add all of the attributes
248
     for (int i=0; i<atts.getLength(); i++) 
249
     {
250
       String attributeName = atts.getQName(i);
251
       String attributeValue = atts.getValue(i);
252
       endNodeId = 
253
                currentNode.setAttribute(attributeName, attributeValue, docid);
254
       
255
       // To handle name space and schema location if the attribute name is
256
       // xsi:schemaLocation. If the name space is in not in catalog table
257
       // it will be regeistered.
258
       if (attributeName != null && 
259
           attributeName.indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1)
260
       {
261
         SchemaLocationResolver resolver = 
262
                                  new SchemaLocationResolver(attributeValue);
263
         resolver.resolveNameSpace();
264
         
265
       }
266
       else if (attributeName !=null && attributeName.equals(ID))
267
       {
268
         // handle subtree info
269
         SubTree subTress = new SubTree();
270
         // set sub tree id
271
         subTress.setSubTreeId(attributeValue);
272
         // set sub tree sstart lement name
273
         subTress.setStartElementName(currentNode.getTagName());
274
         // set start node number
275
         subTress.setStartNodeId(startNodeId);
276
         // add to stack, but it didn't get end node id yet
277
         subTreeInfoStack.push(subTress);
278
         
279
       }
280
     }
281
   
282
     // handle access stuff
283
     if (localName.equals(ACCESS))
284
     {
285
       // if it is in addtionalmetacat
286
       if (parentNode.getTagName() == ADDITIONALMETADATA)
287
       {
288
         processAdditionalAccess = true;
289
        
290
       }
291
       else
292
       {
293
         processTopLeverAccess = true;
294
        
295
       }
296
       // create access object 
297
        accessObject = new AccessSection();
298
         // set permission order
299
       String permOrder = currentNode.getAttribute(ORDER);
300
       accessObject.setPermissionOrder(permOrder);
301
       // set access id
302
       String accessId = currentNode.getAttribute(ID);
303
       accessObject.setAccessSectionId(accessId);
304
       
305
     }
306
     // Set up a access rule for allow
307
     else if (parentNode.getTagName() != null && 
308
       (parentNode.getTagName()).equals(ACCESS) && localName.equals(ALLOW))
309
     {
310
      
311
       accessRule = new AccessRule(); 
312
      
313
       //set permission type "allow"
314
       accessRule.setPermissionType(ALLOW);
315
      
316
     }
317
     // set up an access rule for den
318
     else if (parentNode.getTagName() != null 
319
       && (parentNode.getTagName()).equals(ACCESS) && localName.equals(DENY))
320
     {
321
       accessRule = new AccessRule();
322
       //set permission type "allow"
323
       accessRule.setPermissionType(DENY);
324
     }
325
     // refernce access, then set up access object (setcion) null
326
     else if (parentNode.getTagName() != null 
327
           && (parentNode.getTagName()).equals(ACCESS) 
328
           && localName.equals(REFERENCES))
329
     {
330
       accessObject = null;
331
     }
332
       
333
   
334
     // Add the node to the stack, so that any text data can be
335
     // added as it is encountered
336
     nodeStack.push(currentNode);
337
     // Add the node to the vector used by thread for writing XML Index
338
     nodeIndex.addElement(currentNode);
339
    
340

    
341
  }
342
  
343
   
344
  /** SAX Handler that is called at the end of each XML element */
345
   public void endElement(String uri, String localName,
346
                          String qName) throws SAXException 
347
  {
348
     MetaCatUtil.debugMessage("End ELEMENT " + qName, 50);
349

    
350
     // Get the node from the stack
351
     DBSAXNode currentNode = (DBSAXNode)nodeStack.pop();
352
     String currentTag = currentNode.getTagName();
353
     
354
    
355
     // If before the end element, the parser hit text nodes and store them
356
     // into the buffer, write the buffer to data base. The reason we put
357
     // write database here is for xerces some time split text node
358
     if (hitTextNode)
359
     {
360
        // get access value
361
        String data = null;
362
        // add principal
363
       if (currentTag.equals(PRINCIPAL) && accessRule != null) 
364
       {
365
          data = (textBuffer.toString()).trim();
366
          accessRule.addPrincipal(data);
367

    
368
       } 
369
       else if (currentTag.equals(PERMISSION) && accessRule != null) 
370
       {
371
         data = (textBuffer.toString()).trim();
372
         // we conbine different a permission into one value
373
         int permission = accessRule.getPermission();
374
         // add permision
375
         if ( data.toUpperCase().equals(READSTRING) ) 
376
         {
377
           permission = permission | READ;
378
         } 
379
         else if ( data.toUpperCase().equals(WRITESTRING) ) 
380
         {
381
           permission = permission | WRITE;
382
         } 
383
         else if ( data.toUpperCase().equals(CHMODSTRING)) 
384
         {
385
           permission = permission | CHMOD;
386
         } 
387
         else if ( data.toUpperCase().equals(ALLSTRING) ) 
388
         {
389
          permission = permission | ALL;
390
         }
391
         accessRule.setPermission(permission);
392
       }
393
       // put additionalmetadata/describes into vector
394
       else if (currentTag.equals(DESCRIBES))
395
       {
396
          data = (textBuffer.toString()).trim();
397
          describesId.add(data);
398
       }
399
       else if (currentTag.equals(REFERENCES) && processTopLeverAccess)
400
       {
401
         // get reference 
402
         data = (textBuffer.toString()).trim();
403
         // insert docid and reference id into toplevlerAccess
404
         topLevelAccessControlMap.put(docid, data);
405
         
406
       }
407
       else if (currentTag.equals(REFERENCES) && processAdditionalAccess)
408
       {
409
       
410
          // get reference 
411
          data = (textBuffer.toString()).trim();
412
          // put describeids and reference into additional access mapping
413
          for ( int i=0; i<describesId.size(); i++)
414
          {
415
            String subId = (String)describesId.elementAt(i);
416
            MetaCatUtil.debugMessage("sub id in seting additional mapping: "
417
                                    +subId, 25);
418
            MetaCatUtil.debugMessage("refrence id in setting additional mapping: "
419
                                    +data, 25);
420
            if (subId != null)
421
            {
422
              additionalAccessControlMap.put(subId, data);
423
            }
424
          }
425
          
426
       }
427
       // write text to db if it is not inline data
428
       if (!localName.equals(INLINE))
429
       {
430
          MetaCatUtil.debugMessage("Write text into DB in End Element", 50);
431
          endNodeId = writeTextForDBSAXNode(textBuffer, currentNode);
432
       }
433
       else
434
       {
435
          MetaCatUtil.debugMessage("Write inline data into file system", 25);
436
          // write inline data into file system and return file name
437
          textBuffer = writeInlineDataIntoFile(textBuffer);
438
          // write file name into db
439
          endNodeId = writeTextForDBSAXNode(textBuffer, currentNode);
440
       }
441
     }//if
442
     
443
     //set hitText false
444
     hitTextNode = false;
445
     // reset textbuff
446
     textBuffer = null;
447
     textBuffer = new StringBuffer();
448
     
449
     // hand sub stree stuff
450
     if (!subTreeInfoStack.empty())
451
     {
452
       SubTree tree = (SubTree)subTreeInfoStack.peek();// get last subtree
453
       if (tree != null && tree.getStartElementName() != null && 
454
         (tree.getStartElementName()).equals(currentTag))
455
       {
456
         // find the end of sub tree and set the end node id
457
         tree.setEndNodeId(endNodeId);
458
         // add the subtree into the final store palace
459
         subTreeList.add(tree);
460
         // get rid of it from stack
461
         subTreeInfoStack.pop();
462
       }//if
463
     }//if
464

    
465
     // access stuff
466
     if (currentTag.equals(ALLOW) || currentTag.equals(DENY))
467
     {
468
       // finish parser a ccess rule and  assign it to new one
469
       AccessRule newRule = accessRule;
470
       //add the new rule to access section object
471
       accessObject.addAccessRule(newRule);
472
       // reset access rule
473
       accessRule = null;
474
     }
475
     else if (currentTag.equals(ACCESS))
476
     {
477
       // finish parse a access setction and assign it to new one
478
       AccessSection newAccessObject = accessObject;
479
       if (newAccessObject != null)
480
       {
481
        // add the accessSection into a vector to store it
482
        accessObjectList.add(newAccessObject);
483
        if (processTopLeverAccess)
484
        {
485
          // top level access control will handle whole document -docid
486
          topLevelAccessControlMap.put(docid, newAccessObject);
487
          // reset processtopleveraccess tag
488
          
489
        }//if
490
        else if (processAdditionalAccess)
491
        {
492
          // for additional control
493
          // put everything in describes value and access object into hash
494
          for ( int i=0; i<describesId.size(); i++)
495
          {
496
            String subId = (String)describesId.elementAt(i);
497
            if (subId != null)
498
            {
499
              additionalAccessControlMap.put(subId, newAccessObject);
500
            }//if
501
          }//for
502
         
503
        }//if
504
       }//if
505
       //reset access section object
506
       accessObject = null;
507
       // reset flag
508
       processAdditionalAccess =false;
509
       processTopLeverAccess =false;
510
     }
511
     else if (currentTag.equals(ADDITIONALMETADATA))
512
     {
513
        //reset describesId
514
        describesId = null;
515
        describesId = new Vector();
516
     }
517
   }
518
   
519
   /** SAX Handler that receives notification of end of the document */
520
   public void endDocument() throws SAXException 
521
   {
522
     MetaCatUtil.debugMessage("end Document", 50);
523
     // write access rule to db
524
     writeAccessRuleToDB();
525
     // Starting new thread for writing XML Index.
526
     // It calls the run method of the thread.
527
     try 
528
     {
529
       xmlIndex.start();
530
     } 
531
     catch (NullPointerException e) 
532
     {
533
       xmlIndex = null;
534
       throw new
535
       SAXException("Problem with starting thread for writing XML Index. " +
536
                    e.getMessage());
537
     }
538
   }
539
   
540
  /* The method to write all access rule intodb */
541
  private void writeAccessRuleToDB() throws SAXException
542
  {
543
    //Delete old permssion
544
    deletePermissionsInAccessTable(docid);
545
    //write top leve access rule
546
    writeTopLevelAccessRuleToDB();
547
    //write additional access rule
548
    writeAddtionalAccessRuleToDB();
549
  }//writeAccessRuleToDB
550
   
551
  /* The method to write top level access rule into db. */
552
  private void writeTopLevelAccessRuleToDB() throws SAXException
553
  {
554
    
555
    // for top document level
556
    Object accessSection = topLevelAccessControlMap.get(docid);
557
    boolean top = true;
558
    String subSectionId = null;
559
    // if accessSection is not null and isnot reference
560
    if( accessSection != null && (accessSection instanceof AccessSection) )
561
    {
562
       AccessSection accessObj = (AccessSection)accessSection;
563
       writeGivenAccessRuleIntoDB(accessObj, top, subSectionId);
564
    }//if
565
    else
566
    {
567
      // this is a reference and go trough the vector which contains all
568
      // access object
569
      String referenceId = (String) accessSection;
570
      MetaCatUtil.debugMessage("referered id for top access: "+ 
571
                               referenceId, 25);
572
      for (int i=0; i<accessObjectList.size(); i++)
573
      {
574
        AccessSection accessObj = (AccessSection)accessObjectList.elementAt(i);
575
        String accessObjId = accessObj.getAccessSectionId();
576
        if (referenceId != null && accessObj != null &&
577
            referenceId.equals(accessObjId))
578
        {
579
          writeGivenAccessRuleIntoDB(accessObj, top, subSectionId);
580
        }
581
      }
582
      
583
    }
584
    
585
  }//writeTopLevelAccessRuletoDB
586
   
587
   /* The method to write addtional access rule into db. */
588
  private void writeAddtionalAccessRuleToDB() throws SAXException
589
  {
590
    
591
     PreparedStatement pstmt = null;
592
     // additional access rule
593
     Enumeration en = additionalAccessControlMap.keys();
594
     boolean topLevel =false;
595
   
596
     while(en.hasMoreElements())
597
    {
598
       try
599
       {
600
         // Get subsection id
601
          String subSectionId = (String)en.nextElement();
602
          MetaCatUtil.debugMessage("sub section id in additional access mapping"
603
                                   +"(go through: "+ subSectionId);
604
          
605
          if (subSectionId == null)
606
          {
607
            // if id is null ignore the following lines
608
            continue;
609
          }
610
          // Get AccessSection Object
611
          Object accessSection = additionalAccessControlMap.get(subSectionId);
612
          if (accessSection == null)
613
          {
614
            // if accesssection is null ignore the following lines
615
            continue;
616
          }
617
          else if ( accessSection instanceof AccessSection )
618
          {
619
            // it is not reference
620
            AccessSection accessObj = (AccessSection)accessSection;
621
            writeGivenAccessRuleIntoDB(accessObj, topLevel, subSectionId);
622
          }
623
          else
624
          {
625
            //this is reference
626
            // this is a reference and go trough the vector which contains all
627
            // access object
628
            String referenceId = (String) accessSection;
629
            MetaCatUtil.debugMessage("referered id for additional access "+
630
                                     "mapping(go through): "+ referenceId, 25);
631
            for (int i=0; i<accessObjectList.size(); i++)
632
            {
633
              AccessSection accessObj = 
634
                                (AccessSection)accessObjectList.elementAt(i);
635
              String accessObjId = accessObj.getAccessSectionId();
636
              MetaCatUtil.debugMessage("access obj id in the list(go through): "
637
                                        + accessObjId, 25);
638
              if (referenceId != null && accessObj != null &&
639
                  referenceId.equals(accessObjId))
640
              {
641
                writeGivenAccessRuleIntoDB(accessObj, topLevel, subSectionId);
642
              }//if
643
           }//for
644
      
645
         }//else
646
       }//try
647
       catch (Exception e)
648
       {
649
         
650
         MetaCatUtil.debugMessage("error in EmlSAXHandler.writeAddtionalAccess"
651
                                   + ": "+e.getMessage(), 30);
652
         throw new SAXException(e.getMessage());
653
       }
654
    }//while
655
  }//writeAccessRuletoDB
656
  
657
  /* Write a gaven access rule into db*/
658
  private void writeGivenAccessRuleIntoDB(AccessSection accessSection, 
659
                                         boolean topLevel, String subSectionId) 
660
                                         throws SAXException
661
  {
662
     if (accessSection == null)
663
     {
664
       throw new SAXException("The access object is null");
665
     }
666
     
667
      String permOrder = accessSection.getPermissionOrder();
668
      String sql = null;
669
      PreparedStatement pstmt = null;
670
      if (topLevel)
671
      {
672
        sql = "INSERT INTO xml_access (docid, principal_name, permission, "+
673
                 "perm_type, perm_order, accessfileid) VALUES " +
674
                 " (?, ?, ?, ?, ?, ?)";
675
      }
676
      else
677
      {
678
        sql ="INSERT INTO xml_access (docid,principal_name, "+ 
679
             "permission, perm_type, perm_order, accessfileid, subtreeid, "+
680
             " startnodeid, endnodeid) VALUES" +
681
             " (?, ?, ?, ?, ?, ?, ?, ?, ?)";
682
      }
683
      try 
684
      {
685
     
686
        pstmt = connection.prepareStatement(sql);
687
        // Increase DBConnection usage count
688
        connection.increaseUsageCount(1);
689
        // Bind the values to the query
690
        pstmt.setString(1, docid);
691
        MetaCatUtil.debugMessage("Docid in accesstable: "+ docid, 25);
692
        pstmt.setString(6, docid);
693
        MetaCatUtil.debugMessage("Accessfileid in accesstable: "+ docid, 25);
694
        pstmt.setString(5, permOrder);
695
        MetaCatUtil.debugMessage("PermOder in accesstable: "+ permOrder, 25);
696
        // if it is not top level, set subsection id
697
        if (!topLevel)
698
        {
699
          long startNodeId = 0;
700
          long endNodeId = 0;
701
          // for subtree should specify the
702
          if (subSectionId == null)
703
          {
704
            throw new SAXException("The subsection is null");
705
          }
706
          // go through the substree list vector and found the start node id
707
          // and stop node id for this subtree id
708
          for (int i=0; i<subTreeList.size(); i++)
709
          {
710
            SubTree tree = (SubTree)subTreeList.elementAt(i);
711
            String subTreeId = tree.getSubTreeId();
712
            MetaCatUtil.debugMessage("subtree id in the list(go throug: "+
713
                                      subTreeId, 25);
714
            if (subSectionId.equals(subTreeId))
715
            {
716
              startNodeId = tree.getStartNodeId();
717
              endNodeId = tree.getEndNodeId(); 
718
            }//if
719
          }//for
720
          if (startNodeId == 0 || endNodeId == 0)
721
          {
722
            throw new SAXException("Could find the subtree"
723
                                   + "for this id: "+subSectionId);
724
          }
725
          pstmt.setString(7, subSectionId);
726
          MetaCatUtil.debugMessage("SubSectionId in accesstable: "+ 
727
                                    subSectionId, 25);
728
          pstmt.setLong(8, startNodeId);
729
          MetaCatUtil.debugMessage("Start node id is: " + startNodeId, 25);
730
          pstmt.setLong(9, endNodeId);
731
          MetaCatUtil.debugMessage("End node id is: " + endNodeId, 25);
732
          
733
        }
734
      
735
        Vector accessRules = accessSection.getAccessRules();
736
        // go through every rule
737
        for (int i=0; i<accessRules.size(); i++)
738
        {
739
          AccessRule rule = (AccessRule)accessRules.elementAt(i);
740
          String permType = rule.getPermissionType();
741
          int permission = rule.getPermission();
742
          pstmt.setInt(3, permission);
743
          MetaCatUtil.debugMessage("permission in accesstable: "+ permission, 25);
744
          pstmt.setString(4, permType);
745
          MetaCatUtil.debugMessage("Permtype in accesstable: "+ permType, 25);
746
          // go through every principle in rule
747
          Vector nameVector = rule.getPrincipal();
748
          for ( int j = 0; j < nameVector.size(); j++ ) 
749
          {
750
            String prName = (String)nameVector.elementAt(j);
751
            pstmt.setString(2, prName);
752
            MetaCatUtil.debugMessage("Principal in accesstable: "+prName, 25);
753
            pstmt.execute();
754
          }//for
755
        }//for
756
        pstmt.close();
757
      }//try 
758
      catch (SQLException e) 
759
      {
760
        throw new 
761
        SAXException("EMLSAXHandler.writeAccessRuletoDB(): " + e.getMessage());
762
      }//catch
763
      finally
764
      {
765
        try
766
        {
767
          pstmt.close();
768
        }
769
        catch(SQLException ee)
770
        {
771
          throw new 
772
          SAXException("EMLSAXHandler.writeAccessRuletoDB(): " + 
773
          ee.getMessage());
774
        }
775
      }//finally
776
     
777
  }//writeGivenAccessRuleIntoDB
778
  
779
  /* Delete from db all permission for resources related to @aclid if any.*/
780
  private void deletePermissionsInAccessTable(String aclid) 
781
          throws SAXException 
782
  {
783
    Statement stmt = null;
784
    try
785
    {
786
      // delete all acl records for resources related to @aclid if any
787
      stmt = connection.createStatement();
788
      // Increase DBConnection usage count
789
      connection.increaseUsageCount(1);
790
      stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + aclid +
791
                   "'"); 
792
    
793
    }
794
    catch (SQLException e)
795
    {
796
      throw new SAXException(e.getMessage());
797
    }
798
    finally
799
    {
800
      try
801
      {
802
        stmt.close();
803
      }
804
      catch (SQLException ee)
805
      {
806
        throw new SAXException(ee.getMessage());
807
      }
808
    }
809
  }//deletePermissionsInAccessTable
810
  
811
  // write inline data into file system and return file name(without path)
812
  private StringBuffer writeInlineDataIntoFile(StringBuffer data) 
813
                                               throws SAXException
814
  {
815
    StringBuffer fileNameBuffer = null;
816
    String fileName = null;
817
    String docidWithoutRev = MetaCatUtil.getDocIdFromString(docid);
818
    String path = MetaCatUtil.getOption("inlinedatafilepath");
819
    String seperator = MetaCatUtil.getOption("accNumSeparator");
820
    // the new file name will look like path/docid.rev.2
821
    fileName = docidWithoutRev + seperator+revision+seperator +inLineDataIndex;
822
    File inlineDataDirectory = new File(path);
823
    File newFile = new File(inlineDataDirectory, fileName); 
824
    // incease inLinedataindex for next one
825
    inLineDataIndex++ ;
826
    try
827
    {
828
      FileWriter writer = new FileWriter(newFile);
829
      writer.write(data.toString());
830
    }
831
    catch (Exception e)
832
    {
833
      throw new SAXException(e.getMessage());
834
    }
835
    
836
    fileNameBuffer = new StringBuffer(fileName);
837
    return fileNameBuffer;
838
  }
839
 
840
}
(32-32/54)