Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A class that handles checking permssision for a document
4
               and subtree in a document
5
 *
6
 *  Copyright: 2000 Regents of the University of California and the
7
 *             National Center for Ecological Analysis and Synthesis
8
 *    Authors: Chad Berkley
9
 *
10
 *   '$Author: daigle $'
11
 *     '$Date: 2008-08-05 17:50:14 -0700 (Tue, 05 Aug 2008) $'
12
 * '$Revision: 4213 $'
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
package edu.ucsb.nceas.metacat;
29

    
30
import java.sql.*;
31
import java.util.Enumeration;
32
import java.util.Hashtable;
33
import java.util.Stack;
34
import java.util.Vector;
35
import java.util.Iterator;
36

    
37
import org.apache.log4j.Logger;
38

    
39
import edu.ucsb.nceas.metacat.service.PropertyService;
40
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
41
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
42

    
43
public class PermissionController
44
{
45
   private String docId = null;
46
   private boolean hasSubTreeAccessControl = false; // flag if has a subtree
47
                                                    // access for this docid
48
   private Vector subTreeList = new Vector();
49

    
50
   private long TOPLEVELSTARTNODEID = 0; //if start node is 0, means it is top
51
                                         //level document
52

    
53
   private static Logger logMetacat = Logger.getLogger(PermissionController.class);
54

    
55
   /**
56
    * Constructor for PermissionController
57
    * @param myDocid      the docid need to access
58
    */
59
   public PermissionController(String myDocid) throws McdbException
60
   {
61
     // Get rid of rev number
62
     docId = MetaCatUtil.getSmartDocId(myDocid);
63
     //hasSubTreeAccessControl = checkSubTreeAccessControl();
64
   }
65

    
66
   /**
67
    * Constructor for PermssionController
68
    * @param myDocid String
69
    * @param needDeleteRev boolean
70
    */
71
   public PermissionController(String myDocid, boolean needDeleteRevFromDocid)
72
   {
73
     if (!needDeleteRevFromDocid)
74
     {
75
       docId = myDocid;
76
     }
77
     else
78
     {
79
         docId = MetaCatUtil.getDocIdFromAccessionNumber(myDocid);
80
     }
81
   }
82

    
83
   /**
84
    * Return if a document has subtree access control
85
    */
86
   public boolean hasSubTreeAccessControl()
87
   {
88
     return hasSubTreeAccessControl;
89
   }
90

    
91

    
92
  /**
93
    * Check from db connection if at least one of the list of @principals
94
    * @param user  the user name
95
    * @param groups  the groups which the use is in
96
    * @param myPermission  permission type to check for
97
    */
98
  public boolean hasPermission(String user, String[]groups, String myPermission)
99
                              throws SQLException, Exception
100
  {
101
    boolean hasPermission=false;
102
    String [] userPackage=null;
103
    int permission =AccessControlList.intValue(myPermission);
104

    
105
    //for the commnad line invocation
106
    if ((user==null) && (groups==null || groups.length==0))
107
    {
108
      return true;
109
    }
110

    
111
    //create a userpackage including user, public and group member
112
    userPackage=createUsersPackage(user, groups);
113

    
114
    //if the requested document is access documents and requested permission
115
    //is "write", the user should have "all" right
116

    
117
    if (isAccessDocument(docId) && (permission == AccessControlInterface.WRITE))
118
    {
119

    
120
      hasPermission = hasPermission(userPackage,docId, 7);// 7 is all permission
121
    }//if
122
    else //in other situation, just check the request permission
123
    {
124

    
125

    
126
      // Check for @permission on @docid for @user and/or @groups
127
      hasPermission = hasPermission(userPackage,docId, permission);
128

    
129
    }//else
130

    
131
    return hasPermission;
132
  }
133

    
134

    
135
  /**
136
    * Check from db connection if the users in String array @principals has
137
    * @permission on @docid*
138
    * @param principals, names in userPakcage need to check for @permission
139
    * @param docid, document identifier to check on
140
    * @param permission, permission (write or all...) to check for
141
    */
142
  private boolean hasPermission(String [] principals, String docId,
143
                                           int permission)
144
                         throws SQLException
145
  {
146
    long startId = TOPLEVELSTARTNODEID;// this is for top level, so startid is 0
147
    try
148
    {
149
      //first, if there is a docid owner in user package, return true
150
      //because doc owner has all permssion
151
      if (containDocumentOwner(principals, docId))
152
      {
153

    
154
          return true;
155
      }
156

    
157
      //If there is no owner in user package, checking the table
158
      //check perm_order
159
      if (isAllowFirst(principals, docId, startId))
160
      {
161

    
162
        if (hasExplicitDenyRule(principals, docId, permission, startId))
163
        {
164
          //if it is allowfirst and has deny rule(either explicit )
165
          //deny access
166

    
167
          return false;
168
        }//if
169
        else if ( hasAllowRule(principals, docId, permission, startId))
170
        {
171
          //if it is allowfirst and hasn't deny rule and has allow rule
172
          //allow access
173

    
174
          return true;
175
        }//else if
176
        else
177
        {
178
          //other situation deny access
179

    
180
          return false;
181
        }//else
182
     }//if isAllowFirst
183
     else //denyFirst
184
     {
185
       if (hasAllowRule(principals, docId, permission, startId))
186
       {
187
         //if it is denyFirst and has allow rule, allow access
188
         return true;
189
       }
190
       else
191
       {
192
         //if it is denyfirst but no allow rule, deny access
193
         return false;
194
       }
195
     }//else denyfirst
196
    }//try
197
    catch (Exception e)
198
    {
199
      logMetacat.warn("There is a exception in hasPermission method: "
200
                         +e.getMessage());
201
    }
202

    
203
    return false;
204
  }//hasPermission
205

    
206
  /**
207
   *  Method to check if a person has permission to a inline data file
208
   * @param user String
209
   * @param groups String[]
210
   * @param myPermission String
211
   * @param inlineDataId String
212
   * @throws McdbException
213
   * @return boolean
214
   */
215
  private boolean hasPermissionForInlineData(String user, String[] groups,
216
                                      String myPermission, String inlineDataId)
217
                                      throws Exception
218
  {
219
     // this method can call the public method - hasPermission(...)
220
     // the only difference is about the ownership, you couldn't find the owner
221
     // from inlinedataId directly. You should get it from eml document itself
222
     String []userPackage = createUsersPackage(user, groups);
223
     if (containDocumentOwner(userPackage, docId))
224
     {
225
       return true;
226
     }
227
     else
228
     {
229
         PermissionController controller =
230
                               new PermissionController(inlineDataId, false);
231
         return controller.hasPermission(user, groups, myPermission);
232
     }
233
  }
234

    
235
  /**
236
   * The method to determine of a node can be access by a user just by subtree
237
   * access control
238
   */
239
  public boolean hasPermissionForSubTreeNode(String user, String[] groups,
240
                                             String myPermission, long nodeId)
241
                                             throws McdbException
242
  {
243
    boolean flag = true;
244
    // Get unaccessble subtree for this user
245
    Hashtable unaccessableSubTree = hasUnaccessableSubTree(user, groups,
246
                                                           myPermission);
247
    Enumeration en = unaccessableSubTree.elements();
248
    while (en.hasMoreElements())
249
    {
250
      SubTree tree = (SubTree)en.nextElement();
251
      long start = tree.getStartNodeId();
252
      long stop  = tree.getEndNodeId();
253
      // nodeid in unaccessablesubtree, return false
254
      if ( nodeId >= start && nodeId <= stop)
255
      {
256
        flag = false;
257
        break;
258
      }
259
    }
260
    return flag;
261
  }
262
  /**
263
   * This method will return a hasTable of subtree which user doesn't has the
264
   * permssion to access
265
   * @param user  the user name
266
   * @param groups  the groups which the use is in
267
   * @param myPermission  permission type to check for
268
   */
269
  public Hashtable hasUnaccessableSubTree(String user, String[] groups,
270
                                       String myPermission) throws McdbException
271
  {
272
    Hashtable resultUnaccessableSubTree = new Hashtable();
273
    String [] principals=null;
274
    int permission =AccessControlList.intValue(myPermission);
275

    
276
    //for the commnad line invocation return null(no unaccessable subtree)
277
    if ((user==null) && (groups==null || groups.length==0))
278
    {
279
      return resultUnaccessableSubTree;
280
    }
281

    
282
    //create a userpackage including user, public and group member
283
    principals=createUsersPackage(user, groups);
284
    //for the document owner return null(no unaccessable subtree)
285
    try
286
    {
287
      if (containDocumentOwner(principals, docId))
288
      {
289
       return resultUnaccessableSubTree;
290
      }
291
    }
292
    catch (SQLException ee)
293
    {
294
      throw new McdbException(ee);
295
    }
296

    
297
    // go through every subtree which has access control
298
    for (int i = 0; i< subTreeList.size(); i++)
299
    {
300
      SubTree tree = (SubTree)subTreeList.elementAt(i);
301
      long startId = tree.getStartNodeId();
302

    
303

    
304
        try
305
        {
306
          if (isAllowFirst(principals, docId, startId))
307
          {
308

    
309
            if (hasExplicitDenyRule(principals, docId, permission, startId ))
310
            {
311

    
312
             //if it is allowfirst and has deny rule
313
              // put the subtree into unaccessable vector
314
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
315
              {
316
                resultUnaccessableSubTree.put(new Long(startId), tree);
317
              }
318
            }//if
319
            else if ( hasAllowRule(principals, docId, permission, startId))
320
            {
321
              //if it is allowfirst and hasn't deny rule and has allow rule
322
              //allow access do nothing
323

    
324
            }//else if
325
            else
326
            {
327
              //other situation deny access
328
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
329
              {
330
                resultUnaccessableSubTree.put(new Long(startId), tree);
331
              }
332

    
333
            }//else
334
          }//if isAllowFirst
335
          else //denyFirst
336
          {
337
            if (hasAllowRule(principals, docId, permission,startId))
338
            {
339
              //if it is denyFirst and has allow rule, allow access, do nothing
340

    
341
            }
342
            else
343
            {
344
              //if it is denyfirst but no allow rule, deny access
345
              // add into vector
346
              if (!resultUnaccessableSubTree.containsKey(new Long(startId)))
347
              {
348
                resultUnaccessableSubTree.put(new Long(startId), tree);
349
              }
350
            }
351
          }//else denyfirst
352
        }//try
353
        catch( Exception e)
354
        {
355
          logMetacat.error("error in PermissionControl.has" +
356
                                   "UnaccessableSubTree "+e.getMessage());
357
          throw new McdbException(e);
358
        }
359

    
360
    }//for
361
    // merge the subtree if a subtree is another subtree'subtree
362
    resultUnaccessableSubTree = mergeEquivalentSubtree(resultUnaccessableSubTree);
363
    return resultUnaccessableSubTree;
364
  }//hasUnaccessableSubtree
365

    
366

    
367
  /*
368
   * A method to merge nested subtree into bigger one. For example subtree b
369
   * is a subtree of subtree a. And user doesn't have read permission for both
370
   * so we only use subtree a is enough.
371
   */
372
  private Hashtable mergeEquivalentSubtree(Hashtable unAccessSubTree)
373
  {
374
    Hashtable newSubTreeHash = new Hashtable();
375
    boolean   needDelete = false;
376
    // check the parameters
377
    if (unAccessSubTree == null || unAccessSubTree.isEmpty())
378
    {
379
      return newSubTreeHash;
380
    }
381
    else
382
    {
383
      // look every subtree start point and stop point, to see if it is embedded
384
      // in another one. If embedded, they are equavelent and we can use bigger
385
      // one to replace smaller one
386
      Enumeration en = unAccessSubTree.elements();
387
      while (en.hasMoreElements())
388
      {
389
        SubTree tree    = (SubTree)en.nextElement();
390
        String  treeId  = tree.getSubTreeId();
391
        long    startId = tree.getStartNodeId();
392
        long    endId   = tree.getEndNodeId();
393

    
394
        Enumeration enu = unAccessSubTree.elements();
395
        while (enu.hasMoreElements())
396
        {
397
          SubTree subTree = (SubTree)enu.nextElement();
398
          String subTreeId= subTree.getSubTreeId();
399
          long   subTreeStartId = subTree.getStartNodeId();
400
          long   subTreeEndId   = subTree.getEndNodeId();
401
          //compare and if the first subtree is a subtree of the second
402
          // one, set neeDelete true
403
          if (startId > subTreeStartId && endId < subTreeEndId)
404
          {
405
            needDelete = true;
406
            logMetacat.info("the subtree: "+ treeId +
407
                                     " need to be get rid of from unaccessable"+
408
                                     " subtree list becuase it is a subtree of"+
409
                                     " another subtree in the list");
410
            break;
411
          }//if
412
        }//while
413
        // if not need to delete, put the subtree into hash
414
        if (!needDelete)
415
        {
416
          newSubTreeHash.put(new Long(startId), tree);
417
        }
418
        //reset needDelete
419
        needDelete = false;
420
      }//while
421
      return newSubTreeHash;
422
    }//else
423
  }
424

    
425
  /**
426
	 * Check if a document id is a access document. Access document need user
427
	 * has "all" permission to access it.
428
	 * 
429
	 * @param docId,
430
	 *            the document id need to be checked
431
	 */
432
	private boolean isAccessDocument(String docId) throws SQLException {
433
		// detele the rev number if docid contains it
434
		docId = MetaCatUtil.getDocIdFromString(docId);
435
		PreparedStatement pStmt = null;
436
		DBConnection conn = null;
437
		int serialNumber = -1;
438
		try {
439
			// check out DBConnection
440
			conn = DBConnectionPool.getDBConnection("PermissionControl.isAccessDoc");
441
			serialNumber = conn.getCheckOutSerialNumber();
442
			pStmt = conn.prepareStatement("select doctype from xml_documents where "
443
					+ "docid like '" + docId + "'");
444
			pStmt.execute();
445
			ResultSet rs = pStmt.getResultSet();
446
			boolean hasRow = rs.next();
447
			String doctype = null;
448
			if (hasRow) {
449
				doctype = rs.getString(1);
450

    
451
			}
452
			pStmt.close();
453

    
454
			// if it is an access document
455
			if (doctype != null
456
					&& ((MetaCatUtil.getOptionList(PropertyService
457
							.getProperty("xml.accessdoctype")).contains(doctype)))) {
458

    
459
				return true;
460
			}
461

    
462
		} catch (SQLException e) {
463
			throw new SQLException("PermissionControl.isAccessDocument "
464
					+ "Error checking" + " on document " + docId + ". " + e.getMessage());
465
		} catch (PropertyNotFoundException pnfe) {
466
			throw new SQLException("PermissionControl.isAccessDocument "
467
					+ "Error checking" + " on document " + docId + ". " + pnfe.getMessage());
468
		} finally {
469
			try {
470
				pStmt.close();
471
			} finally {
472
				DBConnectionPool.returnDBConnection(conn, serialNumber);
473
			}
474
		}
475

    
476
		return false;
477
	}// isAccessDocument
478

    
479

    
480

    
481
  /**
482
	 * Check if a stirng array contains a given documents' owner
483
	 * 
484
	 * @param principals,
485
	 *            a string array storing the username, groups name and public.
486
	 * @param docid,
487
	 *            the id of given documents
488
	 */
489
  private boolean containDocumentOwner( String[] principals, String docId)
490
                    throws SQLException
491
  {
492
    int lengthOfArray=principals.length;
493
    boolean hasRow;
494
    PreparedStatement pStmt=null;
495
    DBConnection conn = null;
496
    int serialNumber = -1;
497

    
498
    try
499
    {
500
      //check out DBConnection
501
     conn=DBConnectionPool.getDBConnection("PermissionControl.containDocOnwer");
502
      serialNumber=conn.getCheckOutSerialNumber();
503
      pStmt = conn.prepareStatement(
504
                "SELECT 'x' FROM xml_documents " +
505
                "WHERE docid = ? AND lower(user_owner) = ?");
506
      //check every element in the string array too see if it conatains
507
      //the owner of document
508
      for (int i=0; i<lengthOfArray; i++)
509
      {
510

    
511
        // Bind the values to the query
512
        pStmt.setString(1, docId);
513
        pStmt.setString(2, principals[i]);
514
        logMetacat.info("the principle stack is : " +
515
                                  principals[i]);
516

    
517
        pStmt.execute();
518
        ResultSet rs = pStmt.getResultSet();
519
        hasRow = rs.next();
520
        if (hasRow)
521
        {
522
          pStmt.close();
523
           logMetacat.info("find the owner");
524
          return true;
525
        }//if
526

    
527
      }//for
528
    }//try
529
    catch (SQLException e)
530
    {
531
        pStmt.close();
532

    
533
        throw new
534
        SQLException("PermissionControl.hasPermission(). " +
535
                     "Error checking ownership for " + principals[0] +
536
                     " on document #" + docId + ". " + e.getMessage());
537
    }//catch
538
    finally
539
    {
540
      try
541
      {
542
        pStmt.close();
543
      }
544
      finally
545
      {
546
        DBConnectionPool.returnDBConnection(conn, serialNumber);
547
      }
548
    }
549
    return false;
550
  }//containDocumentOwner
551

    
552
  /**
553
    * Check if the permission order for user at that documents is allowFirst
554
    * @param principals, list of names of principals to check for
555
    * @param docid, document identifier to check for
556
    */
557
  private boolean isAllowFirst(String [] principals, String docId,
558
                               long startId)
559
                  throws SQLException, Exception
560
  {
561
    int lengthOfArray=principals.length;
562
    boolean hasRow;
563
    PreparedStatement pStmt = null;
564
    DBConnection conn = null;
565
    int serialNumber = -1;
566
    String sql = null;
567
    boolean topLever =false;
568
    if (startId == TOPLEVELSTARTNODEID)
569
    {
570
      //top level
571
      topLever = true;
572
      sql = "SELECT perm_order FROM xml_access " +
573
    "WHERE lower(principal_name) = ? AND docid = ? AND startnodeid is NULL";
574
    }
575
    else
576
    {
577
      //sub tree level
578
      sql = "SELECT perm_order FROM xml_access " +
579
        "WHERE lower(principal_name)= ? AND docid = ? AND startnodeid = ?";
580
    }
581

    
582
    try
583
    {
584
      //check out DBConnection
585
      conn=DBConnectionPool.getDBConnection("AccessControlList.isAllowFirst");
586
      serialNumber=conn.getCheckOutSerialNumber();
587

    
588
      //select permission order from database
589
      pStmt = conn.prepareStatement(sql);
590

    
591
      //check every name in the array
592
      for (int i=0; i<lengthOfArray;i++)
593
      {
594
        //bind value
595
        pStmt.setString(1, principals[i]);//user name
596
        pStmt.setString(2, docId);//docid
597

    
598
        // if subtree, we need set subtree id
599
        if (!topLever)
600
        {
601
          pStmt.setLong(3, startId);
602
        }
603

    
604
        pStmt.execute();
605
        ResultSet rs = pStmt.getResultSet();
606
        hasRow=rs.next();
607
        if (hasRow)
608
        {
609
          //get the permission order from data base
610
          String permissionOrder=rs.getString(1);
611
          //if the permission order is "allowFirst
612
          if (permissionOrder.equalsIgnoreCase(AccessControlInterface.ALLOWFIRST))
613
          {
614
            pStmt.close();
615
            return true;
616
          }
617
          else
618
          {
619
            pStmt.close();
620
            return false;
621
          }
622
        }//if
623
      }//for
624
    }//try
625
    catch (SQLException e)
626
    {
627
      throw e;
628
    }
629
    finally
630
    {
631
      try
632
      {
633
        pStmt.close();
634
      }
635
      finally
636
      {
637
        DBConnectionPool.returnDBConnection(conn, serialNumber);
638
      }
639
    }
640

    
641
    //if reach here, means there is no permssion record for given names and
642
    //docid. So throw a exception.
643

    
644
    throw new Exception("There is no permission record for user"+principals[0]+
645
                        "at document "+docId);
646

    
647
  }//isAllowFirst
648

    
649
  /**
650
    * Check if the users array has allow rules for given users, docid and
651
    * permission.
652
    * If it has permission rule and ticket count is greater than 0, the ticket
653
    * number will decrease one for every allow rule
654
    * @param principals, list of names of principals to check for
655
    * @param docid, document identifier to check for
656
    * @param permission, the permssion need to check
657
    */
658
  private boolean hasAllowRule(String [] principals, String docId,
659
                                  int permission, long startId)
660
                  throws SQLException, Exception
661
 {
662
   int lengthOfArray=principals.length;
663
   boolean allow=false;//initial value is no allow rule
664
   ResultSet rs;
665
   PreparedStatement pStmt = null;
666
   int permissionValue=permission;
667
   int permissionValueInTable;
668
   int ticketCount;
669
   DBConnection conn = null;
670
   int serialNumber = -1;
671
   boolean topLever = false;
672
   String sql = null;
673
   if (startId == TOPLEVELSTARTNODEID)
674
   {
675
     // for toplevel
676
     topLever = true;
677
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
678
   "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
679
   }
680
   else
681
   {
682
     topLever =false;
683
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
684
      "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
685
   }
686
   try
687
   {
688
     //check out DBConnection
689
     conn=DBConnectionPool.getDBConnection("AccessControlList.hasAllowRule");
690
     serialNumber=conn.getCheckOutSerialNumber();
691
    //This sql statement will select entry with
692
    //begin_time<=currentTime<=end_time in xml_access table
693
    //If begin_time or end_time is null in table, isnull(begin_time, sysdate)
694
    //function will assign begin_time=sysdate
695
    pStmt = conn.prepareStatement(sql);
696
    //bind docid, perm_type
697
    pStmt.setString(1, docId);
698
    pStmt.setString(3, AccessControlInterface.ALLOW);
699

    
700
    // if subtree lever, need to set subTreeId
701
    if (!topLever)
702
    {
703
      pStmt.setLong(4, startId);
704
    }
705

    
706
    //bind every elenment in user name array
707
    for (int i=0;i<lengthOfArray; i++)
708
    {
709
      pStmt.setString(2, principals[i]);
710
      pStmt.execute();
711
      rs=pStmt.getResultSet();
712
      while (rs.next())//check every entry for one user
713
      {
714
        permissionValueInTable=rs.getInt(1);
715

    
716
        //permission is ok
717
        //the user have a permission to access the file
718
        if (( permissionValueInTable & permissionValue )== permissionValue )
719
        {
720

    
721
           allow=true;//has allow rule entry
722
        }//if
723
      }//while
724
    }//for
725
   }//try
726
   catch (SQLException sqlE)
727
   {
728
     throw sqlE;
729
   }
730
   catch (Exception e)
731
   {
732
     throw e;
733
   }
734
   finally
735
   {
736
     try
737
     {
738
       pStmt.close();
739
     }
740
     finally
741
     {
742
       DBConnectionPool.returnDBConnection(conn, serialNumber);
743
     }
744
   }
745
    return allow;
746
 }//hasAllowRule
747

    
748

    
749

    
750
   /**
751
    * Check if the users array has explicit deny rules for given users, docid
752
    * and permission. That means the perm_type is deny and current time is
753
    * less than end_time and greater than begin time, or no time limit.
754
    * @param principals, list of names of principals to check for
755
    * @param docid, document identifier to check for
756
    * @param permission, the permssion need to check
757
    */
758
  private boolean hasExplicitDenyRule(String [] principals, String docId,
759
                                      int permission, long startId)
760
                  throws SQLException
761
 {
762
   int lengthOfArray=principals.length;
763
   ResultSet rs;
764
   PreparedStatement pStmt = null;
765
   int permissionValue=permission;
766
   int permissionValueInTable;
767
   DBConnection conn = null;
768
   int serialNumber = -1;
769
   String sql = null;
770
   boolean topLevel = false;
771

    
772
   // decide top level or subtree level
773
   if (startId == TOPLEVELSTARTNODEID)
774
   {
775
     topLevel = true;
776
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
777
    "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid is NULL";
778
   }
779
   else
780
   {
781
     topLevel = false;
782
     sql = "SELECT permission FROM xml_access WHERE docid = ? " +
783
     "AND lower(principal_name) = ? AND perm_type = ? AND startnodeid = ?";
784
   }
785

    
786
   try
787
   {
788
     //check out DBConnection
789
     conn=DBConnectionPool.getDBConnection("PermissionControl.hasExplicitDeny");
790
     serialNumber=conn.getCheckOutSerialNumber();
791

    
792
     pStmt = conn.prepareStatement(sql);
793
    //bind docid, perm_type
794
    pStmt.setString(1, docId);
795
    pStmt.setString(3, AccessControlInterface.DENY);
796

    
797
    // subtree level need to set up subtreeid
798
    if (!topLevel)
799
    {
800
      pStmt.setLong(4, startId);
801
    }
802

    
803
    //bind every elenment in user name array
804
    for (int i=0;i<lengthOfArray; i++)
805
    {
806
      pStmt.setString(2, principals[i]);
807
      pStmt.execute();
808
      rs=pStmt.getResultSet();
809
      while (rs.next())//check every entry for one user
810
      {
811
        permissionValueInTable=rs.getInt(1);
812

    
813
        //permission is ok the user doesn't have permission to access the file
814
        if (( permissionValueInTable & permissionValue )== permissionValue )
815

    
816
        {
817
           pStmt.close();
818
           return true;
819
         }//if
820
      }//while
821
    }//for
822
   }//try
823
   catch (SQLException e)
824
   {
825
     throw e;
826
   }//catch
827
   finally
828
   {
829
     try
830
     {
831
       pStmt.close();
832
     }
833
     finally
834
     {
835
       DBConnectionPool.returnDBConnection(conn, serialNumber);
836
     }
837
   }//finally
838
   return false;//no deny rule
839
  }//hasExplicitDenyRule
840

    
841

    
842
  /**
843
    * Creat a users pakages to check permssion rule, user itself, public and
844
    * the gourps the user belong will be include in this package
845
    * @param user, the name of user
846
    * @param groups, the string array of the groups that user belong to
847
    */
848
  private String[] createUsersPackage(String user, String [] groups)
849
  {
850
    String [] usersPackage=null;
851
    int lengthOfPackage;
852

    
853
    if (groups!=null)
854
    {
855
      //if gouprs is not null and user is not public, we should create a array
856
      //to store the groups and user and public.
857
      //So the length of userPackage is the length of group plus two
858
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
859
      {
860
        lengthOfPackage=(groups.length)+2;
861
        usersPackage=new String [lengthOfPackage];
862
        //the first two elements is user self and public
863
        //in order to ignore case sensitive, we transfer user to lower case
864
        if (user != null)
865
        {
866
          usersPackage[0]= user.toLowerCase();
867
          logMetacat.info("after transfer to lower case(not null): "+
868
                                     usersPackage[0]);
869
        }
870
        else
871
        {
872
          usersPackage[0] = user;
873
          usersPackage[0]= user.toLowerCase();
874
          logMetacat.info("after transfer to lower case(null): "+
875
                                     usersPackage[0]);
876
        }
877
        usersPackage[1]=AccessControlInterface.PUBLIC;
878
        //put groups element from index 0 to lengthOfPackage-3 into userPackage
879
        //from index 2 to lengthOfPackage-1
880
        for (int i=2; i<lengthOfPackage; i++)
881
        {
882
          //tansfer group to lower case too
883
          if (groups[i-2] != null)
884
          {
885
            usersPackage[i]=groups[i-2].toLowerCase();
886
          }
887
        } //for
888
      }//if user!=public
889
      else//use=public
890
      {
891
        lengthOfPackage=(groups.length)+1;
892
        usersPackage=new String [lengthOfPackage];
893
        //the first lements is public
894
        usersPackage[0]=AccessControlInterface.PUBLIC;
895
        //put groups element from index 0 to lengthOfPackage-2 into userPackage
896
        //from index 1 to lengthOfPackage-1
897
        for (int i=1; i<lengthOfPackage; i++)
898
        {
899
          if (groups[i-1] != null)
900
          {
901
            usersPackage[i]=groups[i-1].toLowerCase();
902
          }
903
        } //for
904
      }//else user=public
905

    
906
    }//if groups!=null
907
    else
908
    {
909
      //because no groups, the userPackage only need two elements
910
      //one is for user, the other is for public
911
      if (!user.equalsIgnoreCase(AccessControlInterface.PUBLIC))
912
      {
913
        lengthOfPackage=2;
914
        usersPackage=new String [lengthOfPackage];
915
        if (user != null)
916
        {
917
          usersPackage[0]=user.toLowerCase();
918
        }
919
        else
920
        {
921
          usersPackage[0]=user;
922
        }
923
        usersPackage[1]=AccessControlInterface.PUBLIC;
924
      }//if user!=public
925
      else //user==public
926
      {
927
        //only put public into array
928
        lengthOfPackage=1;
929
        usersPackage=new String [lengthOfPackage];
930
        usersPackage[0]=AccessControlInterface.PUBLIC;
931
      }
932
    }//else groups==null
933
    return usersPackage;
934
  }//createUsersPackage
935

    
936

    
937
  /**
938
   * A static method to get Hashtable which cointains a inlinedata object list that
939
   * user can't read it. The key is subtree id of inlinedata, the data is
940
   * internal file name for the inline data which is stored as docid
941
   * in xml_access table or data object doc id.
942
   * @param docidWithoutRev, metadata docid which should be the accessfileid
943
   *                         in the table
944
   * @param user , the name of user
945
   * @param groups, the group which the user belong to
946
   */
947
   public static Hashtable getUnReadableInlineDataIdList(String docidWithoutRev,
948
                                                   String user, String[] groups,
949
                                                   boolean withRevision)
950
                                                throws Exception
951
   {
952
     Hashtable inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
953
                              user, groups, AccessControlInterface.READSTRING,
954
                              withRevision);
955

    
956
     return inlineDataList;
957
   }
958

    
959
   /**
960
  * A static method to get Hashtable which cointains a inline  data object list that
961
  * user can't overwrite it. The key is subtree id of inline data distrubition,
962
  * the value is internal file name for the inline data which is stored as docid
963
  * in xml_access table or data object doc id.
964
  * @param docidWithoutRev, metadata docid which should be the accessfileid
965
  *                         in the table
966
  * @param user , the name of user
967
  * @param groups, the group which the user belong to
968
  */
969
  public static Hashtable getUnWritableInlineDataIdList(String docidWithoutRev,
970
                                                  String user, String[] groups,
971
                                                  boolean withRevision)
972
                                               throws Exception
973
  {
974
    Hashtable inlineDataList = getUnAccessableInlineDataIdList(docidWithoutRev,
975
                            user, groups, AccessControlInterface.WRITESTRING,
976
                            withRevision);
977

    
978
    return inlineDataList;
979
  }
980

    
981

    
982
   /*
983
    * This method will get hashtable which contains a unaccessable distribution
984
    * inlinedata object list
985
    *
986
    * withRevision is used to get inline id list with or without revision number
987
    * e.g. when withRevision is true, temp.1.1.1, temp.1.1.2 would be returned
988
    * otherwise temp.1.1 and temp.1.2 would be returned.
989
    */
990
   private static Hashtable getUnAccessableInlineDataIdList(String docid,
991
                               String user, String[] groups, String permission,
992
                               boolean withRevision)
993
                             throws SQLException,McdbException, Exception
994
   {
995
      Hashtable unAccessbleIdList = new Hashtable();
996
      Hashtable allIdList = getAllInlineDataIdList(docid);
997
      Enumeration en = allIdList.keys();
998
      while (en.hasMoreElements())
999
      {
1000
        String subTreeId = (String) en.nextElement();
1001
        String fileId = (String) allIdList.get(subTreeId);
1002
        //Here fileid is internal file id for line data. It stored in docid
1003
        // field in xml_access table. so we don't need to delete rev
1004
        PermissionController controller = new PermissionController(docid, false);
1005
        if (!controller.hasPermissionForInlineData(user, groups, permission, fileId))
1006
        {
1007
            if(withRevision)
1008
            {
1009
                logMetacat.info("Put subtree id " + subTreeId +
1010
                                         " and " + "inline data file name " +
1011
                                         fileId + " into " + "un" + permission +
1012
                                         " hash");
1013
                unAccessbleIdList.put(subTreeId, fileId);
1014

    
1015
            }
1016
            else
1017
            {
1018
                logMetacat.info("Put subtree id " + subTreeId +
1019
                                         " and " + "inline data file name " +
1020
                                         MetaCatUtil.
1021
                                         getInlineDataIdWithoutRev(fileId) +
1022
                                         " into " + "un" + permission +
1023
                                         " hash");
1024
                unAccessbleIdList.put(subTreeId, MetaCatUtil.
1025
                                      getInlineDataIdWithoutRev(fileId));
1026
            }
1027
        }
1028
      }
1029
      return unAccessbleIdList;
1030
   }
1031

    
1032

    
1033
   /*
1034
    * This method will get a hash table from xml_access table for all records
1035
    * about the inline data. The key is subtree id and data is a inline internal
1036
    * file name
1037
    */
1038
   private static Hashtable getAllInlineDataIdList(String docid) throws SQLException
1039
   {
1040
     Hashtable inlineDataList = new Hashtable();
1041
     String sql = "SELECT subtreeid, docid FROM xml_access WHERE " +
1042
                   "accessfileid = ? AND subtreeid  IS NOT NULL";
1043
     PreparedStatement pStmt=null;
1044
     ResultSet rs=null;
1045
     DBConnection conn=null;
1046
     int serialNumber=-1;
1047
     try
1048
     {
1049
       //check out DBConnection
1050
       conn=DBConnectionPool.getDBConnection("PermissionControl.getDataSetId");
1051
       serialNumber=conn.getCheckOutSerialNumber();
1052
       pStmt=conn.prepareStatement(sql);
1053
       //bind the value to query
1054
       pStmt.setString(1, docid);
1055
       //execute the query
1056
       pStmt.execute();
1057
       rs=pStmt.getResultSet();
1058
       //process the result
1059
       while(rs.next())
1060
       {
1061
         String subTreeId = rs.getString(1);
1062
         String inlineDataId = rs.getString(2);
1063
         if (subTreeId != null && !subTreeId.trim().equals("") &&
1064
            inlineDataId != null && !inlineDataId.trim().equals(""))
1065
         {
1066
           inlineDataList.put(subTreeId, inlineDataId);
1067
         }
1068
      }//while
1069
     }//try
1070
     finally
1071
     {
1072
       try
1073
       {
1074
         pStmt.close();
1075
       }
1076
       finally
1077
       {
1078
         DBConnectionPool.returnDBConnection(conn, serialNumber);
1079
       }
1080
     }//finally
1081
     return inlineDataList;
1082
   }//getAllInlineDataIdList
1083
}
(52-52/67)