Project

General

Profile

« Previous | Next » 

Revision 1381

Added by Jing Tao almost 22 years ago

Delete the file to clean up access table.

View differences:

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

  
27
package edu.ucsb.nceas.metacat;
28

  
29
import edu.ucsb.nceas.morpho.datapackage.PackageUtil;
30
import edu.ucsb.nceas.morpho.datapackage.Triple;
31
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
32

  
33
import java.io.FileOutputStream;
34
import java.io.PrintWriter;
35
import java .io.StringReader;
36
import java.sql.ResultSet;
37
import java.sql.PreparedStatement;
38
import java.sql.SQLException;
39
import java.util.Vector;
40

  
41
import org.apache.xerces.parsers.DOMParser;
42
import org.apache.xpath.XPathAPI;
43
import org.w3c.dom.Attr;
44
import org.w3c.dom.NamedNodeMap;
45
import org.w3c.dom.NodeList;
46
import org.w3c.dom.Document;
47
import org.w3c.dom.Node;
48
import org.w3c.dom.NodeList;
49
import org.w3c.dom.DocumentType;
50
import org.xml.sax.InputSource;
51

  
52

  
53

  
54
/**
55
 * This class is used to clean up access table in knb. It will delete any access
56
 * control rules which are not in access xml doc (someone add them into table
57
 * directly). It will update data set doc according new triples in access table.
58
 */
59

  
60
public class CleanupAccessTable
61
{
62
  private static final String TRIPLESTAG = "//triple";
63
  private static final String IDENTIFIER = "//identifier";
64
  private static final String RELATIONSHIP = "provides access control rules for";
65
  public  static final String DELIMITER = "!";
66
  private static final String DOT = ".";
67
  private static final String LOGFILENAME = "log";
68
  private static final String ALLOW = "allow";
69
  private static final String ALLOWPATH ="//allow";
70
  private static final String DENY = "deny";
71
  private static final String DENYPATH = "//deny";
72
  /**
73
   * A method to add a new triple to a data set doc and update data set doc
74
   * in metacat db
75
   *
76
   * @param accessionNumber  the accession number of the data set doc
77
   * @param newTripleVector  the vector containing new triples need to be added 
78
   *                      into the data set doc
79
   */
80
   public static void addNewTripleIntoDataset(String accessionNumber, 
81
                                             Vector newTripleVector)
82
  {
83
    String docidWithoutVersion = null;
84
    int rev = 0;
85
    // check parameter
86
    if (newTripleVector.size()==0 || accessionNumber == null || 
87
        accessionNumber.equals(""))
88
    {
89
      return;
90
    }
91
    
92
    DocumentImpl doc = null;
93
    try
94
    {
95
      docidWithoutVersion = MetaCatUtil.getDocIdFromString(accessionNumber); 
96
      rev = MetaCatUtil.getVersionFromString(accessionNumber);
97
      doc = new DocumentImpl(accessionNumber);
98
    }
99
    catch (Exception e)
100
    {
101
      MetaCatUtil.debugMessage("error in create an document: "
102
                              + e.getMessage(), 30);
103
      return;
104
    }
105
    String xmlDoc = doc.toString();
106
    
107
    // create new triple collection
108
    TripleCollection newTripleForDataSet = new TripleCollection();
109
    for (int i = 0; i<newTripleVector.size(); i++)
110
    {
111
      //Add new tripe
112
      Triple triple = (Triple)newTripleVector.elementAt(i);
113
      MetaCatUtil.debugMessage("New triple: "+triple.toString(), 30);
114
      newTripleForDataSet.addTriple(triple);
115
    }
116
    xmlDoc = addTriplesToTriplesString(newTripleForDataSet, xmlDoc, TRIPLESTAG);
117
   
118
    // Update accessNumber
119
    Vector oldAccessNumberVector = new Vector();
120
    Vector newAccessNumberVector = new Vector();
121
    oldAccessNumberVector.addElement(accessionNumber);
122
    //increase rev number
123
    rev++;
124
    accessionNumber = docidWithoutVersion + "." + rev;
125
    newAccessNumberVector.addElement(accessionNumber);
126
    xmlDoc = incRevInTriples(xmlDoc, oldAccessNumberVector, 
127
                             newAccessNumberVector, TRIPLESTAG);
128
    
129
  
130
    // update database
131
    StringReader xml = new StringReader(xmlDoc);
132
    String pub = "no";
133
    StringReader dtd = null;
134
    String doAction = "UPDATE";
135
    boolean validate = true;
136
    DBConnection dbConn = null;
137
    int serialNumber = -1;
138
    try
139
    {
140
      dbConn=DBConnectionPool.
141
                  getDBConnection("DBQuery.getDataPackageId");
142
      serialNumber=dbConn.getCheckOutSerialNumber();
143
      DocumentImpl.write(dbConn, xml, pub, dtd, doAction,
144
                       accessionNumber, null, null, validate);
145
      MetaCatUtil.debugMessage("update data set file: "+ accessionNumber, 30);
146
      writeToLogFile("Update data set file: " + accessionNumber);
147
      writeToLogFile("New triples added are: "+ newTripleVector.toString());
148
      writeToLogFile("\n");
149
    }
150
    catch (Exception e)
151
    {
152
      MetaCatUtil.debugMessage("error in addNewTripleIntoDataset: "+
153
                                e.getMessage(), 30);
154
    }
155
    finally
156
    {
157
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
158
    }
159
    
160
  }
161
  
162
    /**
163
   * method to add a collection of triples to a triples string.  this method
164
   * searches for any triples already in the string and appends the new
165
   * ones after the existing ones.  
166
   * @param triples the collection of triples to add
167
   * @param dataPackageString the xml document of data set
168
   * @param triplesTag the trip tag in xml docment
169
   */
170
  private static String addTriplesToTriplesString(TripleCollection triples,
171
                                               String dataPackageString, 
172
                                               String triplesTag)
173
  {
174
    //String triplesTag = morpho.getConfiguration().get("triplesTag", 0);
175
    Document doc = null;
176
    DOMParser parser = new DOMParser();
177
    InputSource in;
178
    StringReader sr;
179
    try
180
    { //parse the wizard created file with existing triples
181
      sr = new StringReader(dataPackageString);
182
      in = new InputSource(sr);
183
    }
184
    catch(Exception fnf)
185
    {
186
      fnf.printStackTrace();
187
      return null;
188
    }
189
    try
190
    {
191
      parser.parse(in);
192
      sr.close();
193
    }
194
    catch(Exception e1)
195
    {
196
      System.err.println(e1.toString());
197
    }
198
    doc = parser.getDocument();
199
    //get the DOM rep of the document with existing triples
200
    NodeList tripleNodeList = triples.getNodeList();
201
    NodeList docTriplesNodeList = null;
202
    
203
    try
204
    {
205
      //find where the triples go in the file
206
      docTriplesNodeList = XPathAPI.selectNodeList(doc, triplesTag);
207
    }
208
    catch(Exception se)
209
    {
210
      System.err.println(se.toString());
211
    }
212
    
213
    Node docNode = doc.getDocumentElement();
214
    for(int j=0; j<tripleNodeList.getLength(); j++)
215
    { //add the triples to the appropriate position in the file
216
      Node n = doc.importNode(tripleNodeList.item(j), true);
217
      int end = docTriplesNodeList.getLength() - 1;
218
      Node triplesNode = docTriplesNodeList.item(end);
219
      Node parent = triplesNode.getParentNode();
220
      if(triplesNode.getNextSibling() == null)
221
      {
222
        parent.appendChild(n);
223
      }
224
      else
225
      {
226
        parent.insertBefore(n, triplesNode.getNextSibling());
227
      }
228
    }
229
    
230
    String docString = PackageUtil.printDoctype(doc);
231
    docString += PackageUtil.print(doc.getDocumentElement());
232
    return docString;
233
  }
234
  
235
  
236
  
237
  private static String incRevInTriples(String xml, Vector oldid, 
238
                                        Vector newid, String triplePath)
239
  {
240
    MetaCatUtil.debugMessage("oldid: " + oldid.toString() + 
241
                             " newid: " + newid.toString(), 30);
242
    Document doc = null;
243
    DOMParser parser = new DOMParser();
244
    InputSource in;
245
    StringReader sr;
246
     try
247
    { //parse the wizard created file with existing triples
248
      sr = new StringReader(xml);
249
      in = new InputSource(sr);
250
    }
251
    catch(Exception fnf)
252
    {
253
      fnf.printStackTrace();
254
      return null;
255
    }
256
    try
257
    {
258
      parser.parse(in);
259
      sr.close();
260
    }
261
    catch(Exception e1)
262
    {
263
      System.err.println(e1.toString());
264
    }
265
    
266
    doc = parser.getDocument();
267
    NodeList tripleList = null;
268
    try
269
    {
270
      //find where the triples go in the file
271
      tripleList = XPathAPI.selectNodeList(doc, triplePath);
272
    }
273
    catch(Exception se)
274
    {
275
      System.err.println("incRevInTriples() : parse threw: " + 
276
                         se.toString());
277
    }
278
    
279
    for(int i=0; i<tripleList.getLength(); i++)
280
    {
281
      Node triple = tripleList.item(i);
282
      NodeList children = triple.getChildNodes();
283
      String sub = null;
284
      String rel = null;
285
      String obj = null;
286
      if(children.getLength() > 2)
287
      {
288
        for(int j=0; j<children.getLength(); j++)
289
        {
290
          Node childNode = children.item(j);
291
          String nodename = childNode.getNodeName().trim().toUpperCase();
292
          if(nodename.equals("SUBJECT") || nodename.equals("OBJECT"))
293
          {
294
            String nodeval;
295
            try
296
            {
297
              nodeval = childNode.getFirstChild().getNodeValue().trim();
298
            }
299
            catch(NullPointerException npe)
300
            {
301
              continue;
302
            }
303
            
304
            if(oldid.contains(nodeval.trim()))
305
            {
306
              String newidS = "";
307
              for(int k=0; k<newid.size(); k++)
308
              {
309
                newidS = (String)newid.elementAt(k);
310
                if(nodeval.trim().equals(oldid.elementAt(k)))
311
                {
312
                  break;
313
                }
314
              }
315
              MetaCatUtil.debugMessage("replacing: " + nodeval + 
316
                                       " with " + newidS, 30);
317
              childNode.getFirstChild().setNodeValue(newidS);
318
            }
319
          }
320
        }
321
      }
322
    }
323
    
324
    //increase the identifier
325
    NodeList identiferList = null; 
326
    try
327
    {
328
      //find where the triples go in the file
329
      identiferList = XPathAPI.selectNodeList(doc, IDENTIFIER);
330
    }
331
    catch(Exception se)
332
    {
333
      System.err.println("incRevInTriples() : parse threw: " + 
334
                         se.toString());
335
    }
336
    
337
    for(int i=0; i<identiferList.getLength(); i++)
338
    {
339
      Node identifierNode = identiferList.item(i);
340
      String nodeName = identifierNode.getNodeName().trim().toUpperCase();
341
      if (nodeName.equals("IDENTIFIER"))
342
      {
343
        String nodeValue = null;
344
        try
345
        {
346
           nodeValue = identifierNode.getFirstChild().getNodeValue().trim();
347
        }
348
        catch(NullPointerException npe)
349
        {
350
          continue;
351
        }
352
        
353
        if(oldid.contains(nodeValue.trim()))
354
        {
355
           String newidS = "";
356
            for(int k=0; k<newid.size(); k++)
357
            {
358
               newidS = (String)newid.elementAt(k);
359
               if(nodeValue.trim().equals(oldid.elementAt(k)))
360
               {
361
                  break;
362
               }
363
            }
364
            MetaCatUtil.debugMessage("replacing: " + nodeValue + 
365
                                      " with " + newidS, 30);
366
            identifierNode.getFirstChild().setNodeValue(newidS);
367
         }
368
      
369
     
370
      }
371
    }
372
    
373
    return PackageUtil.printDoctype(doc) + 
374
           PackageUtil.print(doc.getDocumentElement());
375
  }
376
  
377
 
378
  /*
379
   *Give a docid to find a package accesssionNumber for it.
380
   */
381
   private static String getDataPackageAccessionNumber(String docId)
382
  {
383
    String accessNumber = null;
384
    String packageIdWithoutVersion = null;
385
    String rev = null;
386
    PreparedStatement pStmt = null;
387
    ResultSet rs=null;
388
    String query="SELECT docId from xml_relation where subject = ?";
389
    DBConnection dbConn = null;
390
    int serialNumber = -1;
391
    try
392
    {
393
      dbConn=DBConnectionPool.
394
                  getDBConnection("DBQuery.getDataPackageId");
395
      serialNumber=dbConn.getCheckOutSerialNumber();
396
      pStmt=dbConn.prepareStatement(query);
397
      //bind the value to query
398
      pStmt.setString(1, docId);
399
      //execute the query
400
      pStmt.execute();
401
      rs=pStmt.getResultSet();
402
      //process the result
403
      if (rs.next()) //There are some records for the id in docId fields
404
      {
405
        packageIdWithoutVersion=rs.getString(1);//get data package id
406
      }
407
      pStmt.close();
408
      rev = getRevNumber(packageIdWithoutVersion);
409
      accessNumber = packageIdWithoutVersion+"."+rev;
410
      MetaCatUtil.debugMessage("DataPackageId: "+accessNumber, 50);
411
    }//try
412
    catch (SQLException e)
413
    {
414
      MetaCatUtil.debugMessage("Error in isDataPackageId: "
415
                            +e.getMessage(), 30);
416
    }
417
    finally
418
    {
419
      try
420
      {
421
        pStmt.close();
422
      }//try
423
      catch (SQLException ee)
424
      {
425
        MetaCatUtil.debugMessage("Error in isDataPackageId: "
426
                                                        + ee.getMessage(), 30);
427
      }//catch
428
      finally
429
      {
430
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
431
      }//finally
432
    }//finally
433
    return accessNumber;
434
  }//isDataPackageId()
435
  
436
  /**
437
   * Get a dev number from a given docid(without dev)
438
   */
439
  public static String getRevNumber(String docId) 
440
  {
441
    DBConnection dbConn = null;
442
    int serialNumber = -1;
443
    String query = "SELECT rev from xml_documents where docid = ?";
444
    PreparedStatement pStmt = null;
445
    ResultSet rs = null;
446
    String rev = null;
447
    try
448
    {
449
      dbConn=DBConnectionPool.
450
                  getDBConnection("DBQuery.getDataPackageId");
451
      serialNumber=dbConn.getCheckOutSerialNumber();
452
      pStmt=dbConn.prepareStatement(query);
453
      //bind the value to query
454
      pStmt.setString(1, docId);
455
      //execute the query
456
      pStmt.execute();
457
      rs=pStmt.getResultSet();
458
      //process the result
459
      if (rs.next()) //There are some records for the id in docId fields
460
      {
461
        rev=rs.getString(1);//get data package id
462
      }
463
      pStmt.close();
464
    }
465
    catch (SQLException e)
466
    {
467
      MetaCatUtil.debugMessage("the error in getRevNumber: "+
468
                                e.getMessage(), 30);
469
    }
470
    finally
471
    {
472
      try
473
      {
474
        pStmt.close();
475
      }
476
      catch (SQLException ee)
477
      {
478
        MetaCatUtil.debugMessage("the error in getRevNumber2: "+
479
                                  ee.getMessage(), 30);
480
      }
481
      finally
482
      {
483
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
484
        return rev;
485
      }
486
    }
487
   
488
  }
489
  /**
490
   * Delete a access control rule which is not in access xml document 
491
   */
492
  public static void deleteAccessRule(String aclDocid, String accessRule)
493
  {
494
    String principal  = null;
495
    String allowType  = null;
496
    String permission = null;
497
    String allowOrder = null;
498
    String [] parseAccessRuleArray = null;
499
     DBConnection dbConn = null;
500
    int serialNumber = -1;
501
    String query = "delete from xml_access where accessfileid = ? " +
502
                   "and principal_name = ? and perm_type = ? "+
503
                   "and permission = ? and perm_order = ?";
504
    PreparedStatement pStmt = null;
505
    String rev = null;
506
    // parse the access rule 
507
    parseAccessRuleArray = parseAccessRule(accessRule);
508
    if ( parseAccessRuleArray == null)
509
    {
510
      MetaCatUtil.debugMessage("couldn't parse docid: "+aclDocid, 30);
511
      return;
512
    }
513
    else
514
    {
515
      principal  = parseAccessRuleArray[0];
516
      allowType  = parseAccessRuleArray[1];
517
      permission = parseAccessRuleArray[2];
518
      allowOrder = parseAccessRuleArray[3];
519
      
520
    }
521
    
522
    try
523
    {
524
      dbConn=DBConnectionPool.
525
                  getDBConnection("DBQuery.getDataPackageId");
526
      serialNumber=dbConn.getCheckOutSerialNumber();
527
      pStmt=dbConn.prepareStatement(query);
528
      //bind the value to query
529
      pStmt.setString(1, aclDocid);
530
      pStmt.setString(2, principal);
531
      pStmt.setString(3, allowType);
532
      pStmt.setInt(4, (new Integer(permission)).intValue());
533
      pStmt.setString(5, allowOrder);
534
      //execute the query
535
      pStmt.execute();
536
      pStmt.close();
537
      MetaCatUtil.debugMessage("delete rules: "+accessRule+" for "
538
                               +aclDocid+" in table", 30);
539
      writeToLogFile("Delete rules: "+accessRule+" for "
540
                     +aclDocid+" in xml_access table");
541
    }
542
    catch (SQLException e)
543
    {
544
      MetaCatUtil.debugMessage("the error in deleteAccessRule(): "+
545
                                e.getMessage(), 30);
546
    }
547
    finally
548
    {
549
      try
550
      {
551
        pStmt.close();
552
      }
553
      catch (SQLException ee)
554
      {
555
        MetaCatUtil.debugMessage("the error in getRevNumber2: "+
556
                                  ee.getMessage(), 30);
557
      }
558
      finally
559
      {
560
        DBConnectionPool.returnDBConnection(dbConn, serialNumber);
561
       
562
      }
563
    }
564
  }
565
  
566
  /*
567
   * Add a access control rule which is not in access xml document 
568
   */
569
  public static void addAccessRules(String aclDocid, Vector accessRules)
570
                                    throws Exception
571
  {
572
    String principal  = null;
573
    String allowType  = null;
574
    String permission = null;
575
    String allowOrder = null;
576
    String revOfAcl = null;
577
    String accessionNumberOfAcl = null;
578
    String newAccessionNumerOfAcl = null;
579
    String datasetDocId = null;
580
    String accessionNumberOfDataset = null;
581
    String newAccessionNumberOfDataset = null;
582
    int     revOfDataset = 0;
583
    Vector xmlRuleVector = new Vector();
584
    Vector oldAccessionNumberVector = new Vector();
585
    Vector newAccessionNumberVector = new Vector();
586
    
587
    //checking parameter
588
    if (aclDocid==null|| accessRules==null || accessRules.size() == 0)
589
    {
590
      return;
591
    }
592
    
593
    // get xmlString for acl document
594
    String oldxmlStringofAcl = getXMLStringFromDocId(aclDocid);
595
    
596
    
597
    for(int i = 0; i<accessRules.size(); i++)
598
    {
599
      String oneRule = (String)accessRules.elementAt(i);
600
      // parse the access rule 
601
      String [] parseAccessRuleArray = parseAccessRule(oneRule);
602
      if ( parseAccessRuleArray == null)
603
      {
604
        MetaCatUtil.debugMessage("couldn't parse docid: "+aclDocid, 30);
605
        continue;
606
      }
607
      else
608
      {
609
        principal  = parseAccessRuleArray[0];
610
        allowType  = parseAccessRuleArray[1];
611
        permission = parseAccessRuleArray[2];
612
        allowOrder = parseAccessRuleArray[3];
613
        //only for the allowtype is allow or deny
614
        if (allowType.equals(ALLOW) || allowType.equals(DENY))
615
        {
616
          try
617
          {
618
            String xmlRule = ruleToXML(allowType, principal, permission);
619
            xmlRuleVector.addElement(xmlRule);
620
          }
621
          catch(Exception e)
622
          {
623
            MetaCatUtil.debugMessage("error in ruletoxml: "+e.getMessage(), 30);
624
            continue;
625
          }
626
        }//if
627
        
628
      }//else
629
    }//for
630
    // create new rules xml document
631
    String patchRuleXmlAdded    = createXMLStringForAllAddingRules(xmlRuleVector);
632
    String newACLXmlString = updateACLXml(patchRuleXmlAdded, oldxmlStringofAcl);
633
    MetaCatUtil.debugMessage("new acl xml: "+newACLXmlString, 30);
634
    // update acl file and write back to db
635
    revOfAcl = getRevNumber(aclDocid);
636
    accessionNumberOfAcl = aclDocid+DOT+revOfAcl;
637
    oldAccessionNumberVector.addElement(accessionNumberOfAcl);
638
    MetaCatUtil.debugMessage("old accession number of acl: "+
639
                              accessionNumberOfAcl, 30);
640
    revOfAcl = (new Integer((new Integer(revOfAcl)).intValue()+1)).toString();
641
    newAccessionNumerOfAcl = aclDocid+DOT+revOfAcl;
642
    newAccessionNumberVector.addElement(newAccessionNumerOfAcl);
643
    MetaCatUtil.debugMessage("new accession number of acl: "+
644
                              newAccessionNumerOfAcl, 30);
645
    StringReader xmlAcl = new StringReader(newACLXmlString); 
646
    String pub = "no";
647
    StringReader dtd = null;
648
    String doAction = "UPDATE";
649
    boolean validate = true;
650
    DBConnection dbConn = null;
651
    int serialNumber = -1;
652
    try
653
    {
654
      dbConn=DBConnectionPool.
655
                  getDBConnection("CleanupAccessTable.addAccessRules");
656
      serialNumber=dbConn.getCheckOutSerialNumber();
657
      DocumentImpl.write(dbConn, xmlAcl, pub, dtd, doAction,
658
                       newAccessionNumerOfAcl, null, null, validate);
659
     
660
      writeToLogFile("updated acl file: " + newAccessionNumerOfAcl);
661
      writeToLogFile("New rules added are: "+ patchRuleXmlAdded.toString());
662
    }
663
    finally
664
    {
665
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
666
    }
667
    
668
    // we need to inrease accessnumber in dataset and write it back to db
669
    accessionNumberOfDataset = getDataPackageAccessionNumber(aclDocid);
670
    oldAccessionNumberVector.addElement(accessionNumberOfDataset);
671
    DocumentImpl doc = new DocumentImpl(accessionNumberOfDataset);
672
    String xmlOfDataset = doc.toString();
673
    MetaCatUtil.debugMessage("old access of dataset: "+
674
                              accessionNumberOfDataset, 30);
675
    datasetDocId = MetaCatUtil.getDocIdFromString(accessionNumberOfDataset);
676
    revOfDataset = MetaCatUtil.getVersionFromString(accessionNumberOfDataset);
677
    revOfDataset++;
678
    newAccessionNumberOfDataset = datasetDocId+DOT+revOfDataset;
679
    newAccessionNumberVector.addElement(newAccessionNumberOfDataset);
680
    MetaCatUtil.debugMessage("new accessionNumber of dataset: "+
681
                              newAccessionNumberOfDataset, 30);
682
    String newDatasetString = incRevInTriples(xmlOfDataset, 
683
                                              oldAccessionNumberVector,
684
                                              newAccessionNumberVector,
685
                                              TRIPLESTAG);
686
    StringReader xmlDataset = new StringReader(newDatasetString);
687
    MetaCatUtil.debugMessage("new dataset xml: "+newDatasetString, 30);
688
    try
689
    {
690
      dbConn=DBConnectionPool.
691
                  getDBConnection("CleanupAccessTable.addAccessRules");
692
      serialNumber=dbConn.getCheckOutSerialNumber();
693
      DocumentImpl.write(dbConn, xmlDataset, pub, dtd, doAction,
694
                         newAccessionNumberOfDataset, null, null, validate);
695
     
696
      writeToLogFile("Update data set file: " + newAccessionNumberOfDataset);
697
      writeToLogFile("old accessionNumber: " + 
698
                      oldAccessionNumberVector.toString() +
699
                      " were replaced by: " + 
700
                      newAccessionNumberVector.toString());
701
      writeToLogFile("\n");
702
    }
703
    finally
704
    {
705
      DBConnectionPool.returnDBConnection(dbConn, serialNumber);
706
    }
707
    
708
    
709
  }
710
  
711
  /*
712
   * Method to add rule(xml format ) to the orginal acl xml
713
   */
714
  private static String updateACLXml(String patchXML, String originalXML)
715
  {
716
    Document doc = getDOMDocumentFromString(originalXML);
717
    Document docPatch = getDOMDocumentFromString(patchXML);
718
    NodeList allowInPatch = getNodeList(docPatch, ALLOWPATH);
719
    
720
    NodeList denyInPatch   = getNodeList(docPatch, DENYPATH);
721
   
722
    NodeList allowInOrigin= getNodeList(doc, ALLOWPATH);
723
   
724
    NodeList denyInorigin = getNodeList(doc,DENYPATH);
725
   
726
    
727
    
728
    //for allow rule
729
    
730
    for(int j=0; j<allowInPatch.getLength(); j++)
731
    { 
732
      int end = allowInOrigin.getLength() - 1;
733
      Node allowNode = allowInOrigin.item(end);
734
      Node parent = allowNode.getParentNode();
735
      //add the triples to the appropriate position in the file
736
      Node n = doc.importNode(allowInPatch.item(j), true);
737
      if(allowNode.getNextSibling() == null)
738
      {
739
        parent.appendChild(n);
740
      }
741
      else
742
      {
743
        parent.insertBefore(n, allowNode.getNextSibling());
744
      }
745
    }
746
   
747
    // for deny rule
748
    for (int i=0; i<denyInPatch.getLength(); i++)
749
    {
750
      int endOfDeny = denyInorigin.getLength()-1;
751
      if (endOfDeny != -1)
752
      {
753
        // already has deny rule in access document
754
        Node denyNode = denyInorigin.item(endOfDeny);
755
        Node parentOfDeny = denyNode.getParentNode();
756
        Node n = doc.importNode(denyInPatch.item(i), true);
757
        if (denyNode.getNextSibling() == null)
758
        {
759
          parentOfDeny.appendChild(n);
760
        }
761
        else
762
        {
763
          parentOfDeny.insertBefore(n, denyNode.getNextSibling());
764
        }
765
      }
766
      else
767
      {
768
        // no deny rule in access file, just append the deny rule to allow rule
769
        int end = allowInOrigin.getLength() - 1;
770
        Node allowNode = allowInOrigin.item(end);
771
        Node parent = allowNode.getParentNode();
772
        //add the triples to the appropriate position in the file
773
        Node n = doc.importNode(denyInPatch.item(i), true);
774
        parent.appendChild(n);
775
      
776
      }
777
    }
778
    String docString = PackageUtil.printDoctype(doc);
779
    docString += PackageUtil.print(doc.getDocumentElement());
780
    return docString;
781
  }
782
  
783
  /*
784
   * Transfer a rule to String
785
   */
786
  private static String ruleToXML(String allowType, String principal, 
787
                                  String permission) throws Exception
788
  {
789
     Vector permissionVector = transferPermission(permission);
790
     StringBuffer sb = new StringBuffer();
791
     sb.append("<");
792
     sb.append(allowType);
793
     sb.append(">");
794
     sb.append("<principal>").append(principal).append("</principal>");
795
     // add permission
796
     for ( int i = 0; i < permissionVector.size(); i++)
797
     {
798
        String permissionString = (String)permissionVector.elementAt(i);
799
        sb.append("<permission>").append(permissionString).
800
                                  append("</permission>");
801
     }
802
     sb.append("</");
803
     sb.append(allowType);
804
     sb.append(">");
805
     return sb.toString();
806
  }
807
  
808
  /*
809
   * Method tansfer permission form number(4) to string (read)
810
   */
811
  private static Vector transferPermission(String permission) throws Exception
812
  {
813
    Vector result = new Vector();
814
    String read = "read";
815
    String write = "write";
816
    String all = "all";
817
    int permissionInInt = (new Integer(permission)).intValue();
818
    switch (permissionInInt)
819
    {
820
      case 2:
821
        result.addElement(write);
822
        break;
823
      case 4:
824
        result.addElement(read);
825
        break;
826
      case 6:
827
        result.addElement(write);
828
        result.addElement(read);
829
        break;
830
      case 7:
831
        result.addElement(all);
832
        break;
833
    }//switch
834
    return result; 
835
  }
836
   
837
   
838
  /*
839
   * A method create a complete xml string for given a vector
840
   */
841
  private static String createXMLStringForAllAddingRules(Vector rules)
842
  {
843
    String root = "rule";
844
    StringBuffer sb = new StringBuffer();
845
    sb.append("<?xml version=\"1.0\"?>");
846
    sb.append("<" + root + ">");
847
    
848
    for(int i=0; i<rules.size(); i++)
849
    {
850
      sb.append((String)rules.elementAt(i));
851
    }
852
    sb.append("</" + root + ">");
853
    MetaCatUtil.debugMessage("new xml for adding rules: "+sb.toString(), 30);
854
    return sb.toString();
855
    
856
  }
857
 
858
  /*
859
   * A method to get nodelist for given xmlString and path
860
   */
861
  private static NodeList getNodeList(Document doc, String path)
862
  {
863
     NodeList list = null;
864
     try
865
    {
866
      //find where the triples go in the file
867
      list = XPathAPI.selectNodeList(doc, path);
868
    }
869
    catch(Exception se)
870
    {
871
      System.err.println(se.toString());
872
    }
873
    return list;
874
  }
875
  
876
  /*
877
   * Method to get xml string for given docid 
878
   */
879
  private static String getXMLStringFromDocId(String docId)
880
  {
881
    DocumentImpl doc = null;
882
    String docidWithoutVersion = null;
883
    String rev = null;
884
    String accessionNumber = null;
885
    String xmlDoc = null;
886
    if (docId == null || docId.equals(""))
887
    {
888
      return null;
889
    }
890
    
891
    try
892
    {
893
      docidWithoutVersion = MetaCatUtil.getDocIdFromString(docId); 
894
      rev = getRevNumber(docidWithoutVersion);
895
      accessionNumber = docidWithoutVersion+DOT+rev;
896
      doc = new DocumentImpl(accessionNumber);
897
    }
898
    catch (Exception e)
899
    {
900
      MetaCatUtil.debugMessage("error in create an document: "
901
                              + e.getMessage(), 30);
902
      return null;
903
    }
904
    xmlDoc = doc.toString();
905
    return xmlDoc;
906
  }
907
  
908
 
909
  
910
  /*
911
   * method to get a dom docoument by given a xml string
912
   */ 
913
  private static Document getDOMDocumentFromString(String xml)
914
  {
915
    Document doc = null;
916
    DOMParser parser = new DOMParser();
917
    InputSource in = null;
918
    StringReader sr = null;
919
    String xmlString = null;
920
    //checking parameter
921
    if (xml==null || xml.equals(""))
922
    {
923
      return null;
924
    }
925
       
926
    try
927
    { //parse the wizard created file with existing triples
928
      sr = new StringReader(xml);
929
      in = new InputSource(sr);
930
    }
931
    catch(Exception fnf)
932
    {
933
      fnf.printStackTrace();
934
      return null;
935
    }
936
    try
937
    {
938
      parser.parse(in);
939
      sr.close();
940
    }
941
    catch(Exception e1)
942
    {
943
      System.err.println(e1.toString());
944
      return null;
945
    }
946
    doc = parser.getDocument();
947
    return doc;
948
  }
949
  
950
  /*
951
   * parse the string and get a array cotains principle name(index 0),
952
   * allow type (index1), permission (index2), and allow order(index, 4)
953
   */
954
  private static String[] parseAccessRule(String accessRule)
955
  {
956
    String principal  = null;
957
    String allowType  = null;
958
    String permission = null;
959
    String allowOrder = null;
960
    String [] result  = new String[4];
961
    int count = 0;
962
    int index = 0;
963
    char delimiter = DELIMITER.charAt(0);
964
    
965
    if (accessRule== null)
966
    {
967
      return result;
968
    }
969
    for (int i=0; i<accessRule.length(); i++)
970
    {
971
      
972
      char charInString = accessRule.charAt(i);
973
      // find a symbol !
974
      if (charInString == delimiter)
975
      {
976
        count ++;
977
      }
978
      else
979
      {
980
        continue;
981
      }
982
      
983
      switch (count)
984
      {
985
        case 1:
986
        {
987
          // get principal
988
          principal = accessRule.substring(0, i);
989
          // remeber the index
990
          index = i;
991
          break;
992
        }
993
        case 2:
994
        {
995
          allowType = accessRule.substring(index+1, i);
996
          index = i;
997
          break;
998
        }
999
        case 3:
1000
        {
1001
          permission = accessRule.substring(index+1, i);
1002
          index = i;
1003
          allowOrder = accessRule.substring(index+1, accessRule.length());
1004
          break;
1005
        }
1006
      }//switch
1007
    }//for
1008
    
1009
    // if the string exactly has 3 !, add it to array
1010
    if ( count == 3)
1011
    {
1012
      result[0] = principal;
1013
      result[1] = allowType;
1014
      result[2] = permission;
1015
      result[3] = allowOrder;
1016
    }//if
1017
    return result;
1018
  }
1019
  
1020
  /**
1021
   * A method get acl docid list from xml_access table
1022
   */
1023
  public static Vector readAccessDocIdFromDB()
1024
  {
1025
    Vector docidList = new Vector();
1026
    String docid = null;
1027
    DBConnection conn = null;
1028
    int serialNumber = -1;
1029
    PreparedStatement pstmt = null;
1030
    try
1031
    {
1032
      //get connection from DBConnectionPool
1033
      conn = DBConnectionPool.
1034
              getDBConnection("CleanupAccessTable.readAccessDocIdFromDB");
1035
      serialNumber=conn.getCheckOutSerialNumber();
1036
      
1037
      // delete all acl records for resources related to @aclid if any
1038
      pstmt = conn.prepareStatement("SELECT accessfileid FROM xml_access");
1039
      pstmt.execute();
1040
      ResultSet rs = pstmt.getResultSet();
1041
      boolean hasRows = rs.next();
1042
      int i = 0;
1043
      while (hasRows) 
1044
      {
1045
        docid  = rs.getString(1);
1046
        // if hashtable doesn't has the rule add to hashtable
1047
        if (docid !=null && !docidList.contains(docid))
1048
        {
1049
          docidList.addElement(docid);
1050
          
1051
        }
1052
        hasRows = rs.next();
1053
        // reset value
1054
        docid = null;
1055
        
1056
      }//while
1057
  
1058
    }
1059
    catch (SQLException e)
1060
    {
1061
      MetaCatUtil.debugMessage("error in readAccessDocIdFromDB: "+
1062
                              e.getMessage(), 30);
1063
    }
1064
    finally
1065
    {
1066
      try
1067
      {
1068
        pstmt.close();
1069
      }
1070
      catch (SQLException ee)
1071
      {
1072
        MetaCatUtil.debugMessage("error in readAccessDocIdFromDB: "+
1073
                                 ee.getMessage(), 30);
1074
      }
1075
      finally
1076
      {
1077
        //retrun DBConnection
1078
        DBConnectionPool.returnDBConnection(conn,serialNumber);
1079
        return docidList;
1080
      }
1081
    }
1082
 
1083
  }
1084
  
1085
  /**
1086
   * Method to delete rules which is not in xml access file
1087
   */
1088
  public static void addAccessRulesToDocument(String aclDocId, 
1089
                                              Vector rulesFromDB,
1090
                                              Vector rulesFromDocument) 
1091
  {
1092
    
1093
    try
1094
    {
1095
      Vector rulesAdded = new Vector();
1096
      //check for every rules
1097
      for (int j=0; j< rulesFromDB.size(); j++)
1098
      {
1099
        String oneRule = (String)rulesFromDB.elementAt(j);
1100
        // if onerules get from db not in xml_access, delete it
1101
        if (!rulesFromDocument.contains(oneRule))
1102
        {
1103
          MetaCatUtil.debugMessage("one rule: "+oneRule, 30);
1104
          rulesAdded.addElement(oneRule);
1105
        }//if
1106
        oneRule = null;
1107
      }//for
1108
      addAccessRules(aclDocId, rulesAdded);
1109
    }
1110
    catch (Exception e)
1111
    {
1112
      MetaCatUtil.debugMessage("error delete addAccessRulesToDocument(): "+
1113
                                e.getMessage(), 30);
1114
    } 
1115
  }
1116
  
1117
  /**
1118
   * Method to updata data set files
1119
   */
1120
  public static void updateDataSetFilesForNewTriples(String aclDocId,
1121
                                                     Vector docidFromAccessDB, 
1122
                                                     Vector docidFromRelationDB) 
1123
  {
1124
    String aclAccessionNumber = null;
1125
    String revForAcl = null;
1126
    String packagAccessionNumber = null;
1127
    //checking for every acl id
1128
    
1129
    try
1130
    {
1131
      //Get package and acl access number
1132
      packagAccessionNumber = getDataPackageAccessionNumber(aclDocId);
1133
      revForAcl = getRevNumber(aclDocId);
1134
      aclAccessionNumber = aclDocId+DOT+revForAcl;
1135
      //check for every docid in relation ship
1136
      Vector newTripleVector = new Vector();
1137
      for (int j=0; j<docidFromAccessDB.size(); j++)
1138
      {
1139
        String objectId = (String)docidFromAccessDB.elementAt(j);
1140
        String objectAccessionNumber = null;
1141
        String revForObject = null;
1142
        // new triple
1143
        if (!docidFromRelationDB.contains(objectId))
1144
        {
1145
          revForObject = getRevNumber(objectId);
1146
          objectAccessionNumber = objectId+DOT+revForObject;
1147
          Triple newTriple = new Triple(aclAccessionNumber, RELATIONSHIP, 
1148
                                        objectAccessionNumber);
1149
          newTripleVector.add(newTriple);
1150
          MetaCatUtil.debugMessage("find a new triple"+
1151
                                      newTriple.toString(), 30);
1152
          
1153
        }//if
1154
      }//for
1155
      // add new trip into data set
1156
      addNewTripleIntoDataset(packagAccessionNumber, newTripleVector);
1157
     
1158
    }
1159
    catch (Exception e)
1160
    {
1161
        MetaCatUtil.debugMessage("error in updataDatasetFiles(): "+
1162
                                  e.getMessage(), 30);
1163
    }
1164
      
1165
  
1166
  }
1167
  
1168
  /*
1169
   * Method to write information into log file
1170
   */
1171
  private static void writeToLogFile(String message)
1172
  {
1173
    try
1174
    {
1175
      FileOutputStream fos = new FileOutputStream(LOGFILENAME, true);
1176
      PrintWriter pw = new PrintWriter(fos);
1177
      pw.println(message);
1178
      pw.flush();
1179
    }
1180
    catch(Exception e)
1181
    {
1182
      MetaCatUtil.debugMessage("error writing to log: " + e.getMessage(), 30);
1183
     
1184
    }
1185
  }
1186
  
1187
  public static void main(String[] agus)
1188
  {
1189
    
1190
    try
1191
    {
1192
      DBConnectionPool pool = DBConnectionPool.getInstance();
1193
      Vector aclVector = readAccessDocIdFromDB();
1194
      for (int i = 0; i < aclVector.size(); i++)
1195
      {
1196
        try
1197
        {
1198
          String aclDocId = (String)aclVector.elementAt(i);
1199
          AccessRulesFromDocument xmlDocument = new 
1200
                                            AccessRulesFromDocument(aclDocId);
1201
          AccessRulesFromDB db = new AccessRulesFromDB(aclDocId);
1202
          Vector ruleFromDocument = xmlDocument.getAccessRuleVector();
1203
          Vector ruleFromDB = db.getAccessRuleVector();
1204
          Vector docIdFromRelation = xmlDocument.getACLObjects();
1205
          Vector docIdFromAccess = db.getDocidAccessRuleApplied();
1206
          // update rules in acl and triple in dataset file
1207
          addAccessRulesToDocument(aclDocId, ruleFromDB, ruleFromDocument);
1208
          //update triplse in dataset file
1209
          updateDataSetFilesForNewTriples(aclDocId, docIdFromAccess, 
1210
                                          docIdFromRelation);
1211
        }
1212
        catch (Exception e)
1213
        {
1214
           MetaCatUtil.debugMessage("exception in main is: " +
1215
                                    e.getMessage(), 30);
1216
        }
1217
        
1218
      }
1219
    }
1220
    catch(Exception ee)
1221
    {
1222
      MetaCatUtil.debugMessage("exception is: "+ee.getMessage(), 30);
1223
    }
1224
  }
1225
  
1226
}//cleanupAccessTable
1227 0

  

Also available in: Unified diff