Project

General

Profile

« Previous | Next » 

Revision 5089

Added by daigle about 15 years ago

Move access control source to it's own directory.

View differences:

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

  
28
package edu.ucsb.nceas.metacat;
29

  
30
import java.io.*;
31
import java.sql.*;
32
import java.util.Stack;
33
import java.util.Vector;
34

  
35
import org.apache.log4j.Logger;
36
import org.xml.sax.Attributes;
37
import org.xml.sax.InputSource;
38
import org.xml.sax.ContentHandler;
39
import org.xml.sax.EntityResolver;
40
import org.xml.sax.ErrorHandler;
41
import org.xml.sax.SAXException;
42
import org.xml.sax.XMLReader;
43
import org.xml.sax.helpers.XMLReaderFactory;
44
import org.xml.sax.helpers.DefaultHandler;
45

  
46
import edu.ucsb.nceas.metacat.database.DBConnection;
47
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
48
import edu.ucsb.nceas.metacat.properties.PropertyService;
49
import edu.ucsb.nceas.metacat.util.MetacatUtil;
50
import edu.ucsb.nceas.metacat.util.SystemUtil;
51
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
52

  
53
/** 
54
 * A Class that loads eml-access.xml file containing ACL for a metadata
55
 * document into relational DB. It extends DefaultHandler class to handle
56
 * SAX parsing events when processing the XML stream.
57
 */
58
public class AccessControlList extends DefaultHandler 
59
                               implements AccessControlInterface 
60
{
61

  
62
 
63
//  private static String sysdate = DatabaseService.getDBAdapter().getDateTimeFunction();
64
//  private static String isnull = DatabaseService.getDBAdapter().getIsNULLFunction();
65
  
66
  private DBConnection connection;
67
  private String parserName;
68
  private Stack elementStack;
69
  private String server;
70
  private String sep;
71
 
72
  private boolean	processingDTD;
73
  private String  user;
74
  private String[] groups;
75
  private String  aclid;
76
  private int     rev;
77
  private String 	docname;
78
  private String 	doctype;
79
  private String 	systemid;
80

  
81
  private String docurl;
82
  private Vector resourceURL;
83
  private Vector resourceID;
84
  private Vector principal;
85
  private int    permission;
86
  private String permType;
87
  private String permOrder;
88
//  private String publicAcc;
89
  private String beginTime;
90
  private String endTime;
91
  private int    ticketCount;
92
  private int    serverCode = 1;
93

  
94
  private Vector aclObjects = new Vector();
95
  private boolean instarttag = true;
96
  private String tagName = "";
97
  
98
  private static Logger logMetacat = Logger.getLogger(AccessControlList.class);
99
  /**
100
   * Construct an instance of the AccessControlList class.
101
   * It is used by the permission check up from DBQuery or DocumentImpl
102
   * and from "getaccesscontrol" action
103
   *
104
   * @param conn the JDBC connection where acl info is get
105
   */
106
  public AccessControlList(DBConnection conn) throws SQLException
107
  {
108
    this.connection = conn;
109
  }
110
  
111

  
112
  
113

  
114
  /**
115
   * Construct an instance of the AccessControlList class.
116
   * It parse acl file and loads acl data into db connection.
117
   *
118
   * @param conn the JDBC connection where acl data are loaded
119
   * @param aclid the Accession# of the document with the acl data
120
   * @param acl the acl file containing acl data
121
   * @param user the user connected to MetaCat servlet and owns the document
122
   * @param groups the groups to which user belongs
123
   * @param serverCode the serverid from xml_replication on which this document
124
   *        resides.
125
   */
126
  public AccessControlList(DBConnection conn, String aclid, int rev,
127
                           String user, String[] groups, int serverCode)
128
                  throws SAXException, IOException, McdbException, PropertyNotFoundException
129
  {
130
		String parserName = PropertyService.getProperty("xml.saxparser");
131
		this.server = SystemUtil.getSecureServerURL();
132
		this.sep = PropertyService.getProperty("document.accNumSeparator");
133

  
134
		this.connection = conn;
135
		this.parserName = parserName;
136
		this.processingDTD = false;
137
		this.elementStack = new Stack();
138

  
139
		this.user = user;
140
		this.groups = groups;
141
		this.aclid = aclid;
142
		this.resourceURL = new Vector();
143
		this.resourceID = new Vector();
144
		this.principal = new Vector();
145
		this.permission = 0;
146
		this.ticketCount = 0;
147
		// this.publicAcc = null;
148
		this.serverCode = serverCode;
149

  
150
		// read the access file from db connection
151
		DocumentImpl acldoc = new DocumentImpl(aclid + sep + rev);
152
		String acl = acldoc.toString();
153
		this.rev = acldoc.getRev();
154

  
155
		// Initialize the parse
156
		XMLReader parser = initializeParser();
157
		// parse the access file and write the info to xml_access
158
		if (acl != null) {
159
			parser.parse(new InputSource(new StringReader(acl)));
160
		} else {
161
			throw new McdbException("Could not retrieve access control list for:  " + aclid + sep + rev);
162
		}
163
	}
164

  
165
// NOT USED
166
// /**
167
// * Construct an instance of the AccessControlList class.
168
//   * It parses eml-access file and loads acl data into db connection.
169
//   * It is used from command line execution.
170
//   *
171
//   * @param conn the JDBC connection where acl data are loaded
172
//   * @param docid the Accession# of the document with the acl data
173
//   * @param aclfilename the name of acl file containing acl data
174
//   * @param user the user connected to MetaCat servlet and owns the document
175
//   * @param groups the groups to which user belongs
176
//   */
177
//  public AccessControlList( Connection conn, String aclid, String aclfilename,
178
//                           String user, String[] groups )
179
//                  throws SAXException, IOException, McdbException
180
//  {
181
//    this(conn, aclid, new FileReader(new File(aclfilename).toString()), 
182
//         user, groups, 1);
183
//  }
184
  
185
  /* Set up the SAX parser for reading the XML serialized ACL */
186
  private XMLReader initializeParser() throws SAXException 
187
  {
188
    XMLReader parser = null;
189

  
190
    // Get an instance of the parser
191
    parser = XMLReaderFactory.createXMLReader(parserName);
192

  
193
    // Turn off validation
194
    parser.setFeature("http://xml.org/sax/features/validation", true);
195
      
196
    // Set Handlers in the parser
197
    // Set the ContentHandler to this instance
198
    parser.setContentHandler((ContentHandler)this);
199

  
200
    // make a DBEntityResolver instance
201
    // Set the EntityReslover to DBEntityResolver instance
202
    EntityResolver eresolver = new DBEntityResolver(connection,this,null);
203
    parser.setEntityResolver((EntityResolver)eresolver);
204

  
205
    // Set the ErrorHandler to this instance
206
    parser.setErrorHandler((ErrorHandler)this);
207

  
208
    return parser; 
209
  }
210
  
211
  /**
212
   * Callback method used by the SAX Parser when beginning of the document
213
   */
214
  public void startDocument() throws SAXException 
215
  {
216
    //delete all previously submitted permissions @ relations
217
    //this happens only on UPDATE of the access file
218
    try {
219
      this.aclObjects = getACLObjects(aclid);
220

  
221
      //delete all permissions for resources related to @aclid if any
222
      if ( aclid != null ) {
223
        deletePermissionsForRelatedResources(aclid);
224
      }
225
    } catch (SQLException sqle) {
226
      throw new SAXException(sqle);
227
    }
228
  }
229
  
230
  /**
231
   * Callback method used by the SAX Parser when the start tag of an 
232
   * element is detected. Used in this context to parse and store
233
   * the acl information in class variables.
234
   */
235
  public void startElement (String uri, String localName, 
236
                            String qName, Attributes atts) 
237
         throws SAXException 
238
  {
239
    instarttag = true;
240
    if(localName.equals("allow"))
241
    {
242
      tagName = "allow";
243
    }
244
    else if(localName.equals("deny"))
245
    {
246
      tagName = "deny";
247
    }
248
    BasicNode currentNode = new BasicNode(localName);
249
    if (atts != null) {
250
      int len = atts.getLength();
251
      for (int i = 0; i < len; i++) {
252
        currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i));
253
      }
254
    }
255
    if ( currentNode.getTagName().equals("acl") ) {
256
      permOrder = currentNode.getAttribute("order");
257
    //  publicAcc = currentNode.getAttribute("public");
258
    }
259
    elementStack.push(currentNode); 
260
  }
261

  
262
  /**
263
   * Callback method used by the SAX Parser when the text sequences of an 
264
   * xml stream are detected. Used in this context to parse and store
265
   * the acl information in class variables.
266
   */ 
267
  public void characters(char ch[], int start, int length)
268
         throws SAXException 
269
  {
270
    if(!instarttag)
271
    {
272
      return;
273
    }
274
    String inputString = new String(ch, start, length);
275
    inputString = inputString.trim(); 
276
    //System.out.println("==============inputString: " + inputString);
277
    BasicNode currentNode = (BasicNode)elementStack.peek(); 
278
    String currentTag = currentNode.getTagName();
279

  
280
      if (currentTag.equals("principal")) {
281

  
282
        principal.addElement(inputString);
283

  
284
      } else if (currentTag.equals("permission")) {
285

  
286
        if ( inputString.trim().toUpperCase().equals("READ") ) {
287
          permission = permission | READ;
288
        } else if ( inputString.trim().toUpperCase().equals("WRITE") ) {
289
          permission = permission | WRITE;
290
        } else if ( inputString.trim().toUpperCase().equals("CHANGEPERMISSION")) 
291
        {
292
          permission = permission | CHMOD;
293
        } else if ( inputString.trim().toUpperCase().equals("ALL") ) {
294
          permission = permission | ALL;
295
        }/*else{
296
          throw new SAXException("Unknown permission type: " + inputString);
297
        }*/
298

  
299
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
300
        beginTime = inputString.trim();
301

  
302
      } else if ( currentTag.equals("stopDate") && endTime == null) {
303
        endTime = inputString.trim();
304

  
305
      } else if (currentTag.equals("ticketCount") && ticketCount == 0 ) {
306
        try {
307
          ticketCount = (new Integer(inputString.trim())).intValue();
308
        } catch (NumberFormatException nfe) {
309
          throw new SAXException("Wrong integer format for:" + inputString);
310
        }
311
      }
312
  }
313

  
314
  /**
315
   * Callback method used by the SAX Parser when the end tag of an 
316
   * element is detected. Used in this context to parse and store
317
   * the acl information in class variables.
318
   */
319
  public void endElement (String uri, String localName, String qName)
320
         throws SAXException 
321
  {
322
    instarttag = false;
323
    BasicNode leaving = (BasicNode)elementStack.pop();
324
    String leavingTagName = leaving.getTagName();
325

  
326
    if ( leavingTagName.equals("allow") ||
327
         leavingTagName.equals("deny")    ) {
328
      
329
      if ( permission > 0 ) {
330

  
331
        // insert into db calculated permission for the list of principals
332
        try {
333
          // go through the objects in xml_relation about this acl doc
334
          for (int i=0; i < aclObjects.size(); i++) {
335
            // docid of the current object
336
            String docid = (String)aclObjects.elementAt(i); 
337
            //DocumentIdentifier docID = new DocumentIdentifier(docid);
338
            //docid = docID.getIdentifier();
339
            // the docid get here has revision number, so we need to 
340
            // remove it.
341
            //docid = MetacatUtil.getDocIdFromAccessionNumber(docid);
342
            //System.out.println("The docid insert is!!!!!!!!!! "+ docid);
343
            insertPermissions(docid,leavingTagName);
344
          }
345
          
346
          // if acl is not in object list
347
          //should insert permission for aclid itself into database
348
          /*if (!aclObjects.contains(aclid))
349
          {
350
            DocumentIdentifier aclIdItself = new DocumentIdentifier(aclid);
351
            String aclIdString = aclIdItself.getIdentifier();
352
            insertPermissions(aclIdString,leavingTagName);
353
          }*/
354
          
355

  
356
        } catch (SQLException sqle) {
357
          throw new SAXException(sqle);
358
        } catch (Exception e) {
359
          throw new SAXException(e);
360
        }
361
      }
362

  
363
      // reset the allow/deny permission
364
      principal = new Vector();
365
      permission = 0;
366
      beginTime = null;
367
      endTime = null;
368
      ticketCount = 0;
369
    
370
    }
371

  
372
  }
373

  
374
  /** 
375
    * SAX Handler that receives notification of DOCTYPE. Sets the DTD.
376
    * @param name name of the DTD
377
    * @param publicId Public Identifier of the DTD
378
    * @param systemId System Identifier of the DTD
379
    */
380
  public void startDTD(String name, String publicId, String systemId) 
381
              throws SAXException {
382
    docname = name;
383
    doctype = publicId;
384
    systemid = systemId;
385
  }
386

  
387
  /** 
388
   * SAX Handler that receives notification of the start of entities.
389
   * @param name name of the entity
390
   */
391
  public void startEntity(String name) throws SAXException {
392
    if (name.equals("[dtd]")) {
393
      processingDTD = true;
394
    }
395
  }
396

  
397
  /** 
398
   * SAX Handler that receives notification of the end of entities.
399
   * @param name name of the entity
400
   */
401
  public void endEntity(String name) throws SAXException {
402
    if (name.equals("[dtd]")) {
403
      processingDTD = false;
404
    }
405
  }
406

  
407
  /**
408
   * Get the document name.
409
   */
410
  public String getDocname() {
411
    return docname;
412
  }
413

  
414
  /**
415
   * Get the document processing state.
416
   */
417
  public boolean processingDTD() {
418
    return processingDTD;
419
  }
420
  
421
  /* Get all objects associated with @aclid from db.*/
422
  private Vector getACLObjects(String aclid) 
423
          throws SQLException 
424
  {
425
    Vector aclObjects = new Vector();
426
    DBConnection conn = null;
427
    int serialNumber = -1;
428
    PreparedStatement pstmt = null;
429
    try
430
    {
431
      //get connection from DBConnectionPool
432
      conn=DBConnectionPool.getDBConnection("AccessControlList.getACLObject");
433
      serialNumber=conn.getCheckOutSerialNumber();
434
      
435
      // delete all acl records for resources related to @aclid if any
436
      pstmt = conn.prepareStatement(
437
                             "SELECT object FROM xml_relation " +
438
                             "WHERE subject = ? ");
439
      pstmt.setString(1,aclid);
440
      pstmt.execute();
441
      ResultSet rs = pstmt.getResultSet();
442
      boolean hasRows = rs.next();
443
      while (hasRows) {
444
        String object = rs.getString(1);
445
        //System.out.println("add acl object into vector !!!!!!!!!!!!!!!!!"+object);
446
        aclObjects.addElement(object);
447
        hasRows = rs.next();
448
      }//whil
449
    }
450
    catch (SQLException e)
451
    {
452
      throw e;
453
    }
454
    finally
455
    {
456
      try
457
      {
458
        pstmt.close();
459
      }
460
      finally
461
      {
462
        //retrun DBConnection
463
        DBConnectionPool.returnDBConnection(conn,serialNumber);
464
      }
465
    }
466
    
467
    return aclObjects;
468
  }
469

  
470
  /* Delete from db all permission for resources related to @aclid if any.*/
471
  private void deletePermissionsForRelatedResources(String aclid) 
472
          throws SQLException 
473
  {
474
    //DBConnection conn = null;
475
    //int serialNumber = -1;
476
    Statement stmt = null;
477
    try
478
    {
479
      //check out DBConenction
480
      //conn=DBConnectionPool.getDBConnection("AccessControlList.deltePerm");
481
      //serialNumber=conn.getCheckOutSerialNumber();
482
      // delete all acl records for resources related to @aclid if any
483
      stmt = connection.createStatement();
484
      // Increase DBConnection usage count
485
      connection.increaseUsageCount(1);
486
      logMetacat.debug("running sql: " + stmt.toString());
487
      stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + aclid 
488
                                                                      + "'");
489
      //increase usageCount!!!!!!
490
      //conn.increaseUsageCount(1);
491
    }
492
    catch (SQLException e)
493
    {
494
      throw e;
495
    }
496
    finally
497
    {
498
      stmt.close();
499
      //retrun DBConnection
500
      //DBConnectionPool.returnDBConnection(conn,serialNumber);
501
    }
502
  }
503

  
504
  /* Insert into db calculated permission for the list of principals 
505
   * The DBConnection it is use is class field. Because we want to keep rollback
506
   * features and it need use same connection
507
  */
508
  
509
  private void insertPermissions(String docid, String permType ) 
510
                                            throws SQLException 
511
  {
512
    PreparedStatement pstmt = null;
513
    //DBConnection conn = null;
514
    //int serialNumber = -1;
515
    try {
516
      //Check out DBConnection
517
      //conn=DBConnectionPool.getDBConnection("AccessControlList.insertPerm");
518
      //serialNumber=conn.getCheckOutSerialNumber();
519
      
520
      pstmt = connection.prepareStatement(
521
              "INSERT INTO xml_access " + 
522
              "(docid, principal_name, permission, perm_type, perm_order," +
523
              "ticket_count, accessfileid) VALUES " +
524
              "(?,?,?,?,?,?,?)");
525
      // Increase DBConnection usage count
526
      connection.increaseUsageCount(1);
527
      // Bind the values to the query
528
      pstmt.setString(1, docid);
529
      pstmt.setInt(3, permission);
530
      pstmt.setString(4, permType);
531
      pstmt.setString(5, permOrder);
532
      pstmt.setString(7, aclid);
533
      if ( ticketCount > 0 ) {
534
        pstmt.setInt(6, ticketCount);
535
      } else {
536
        pstmt.setInt(6, 0);
537
      }
538
      
539
      //incrase usagecount for DBConnection
540
      //conn.increaseUsageCount(1);
541
      String prName;
542
      for ( int j = 0; j < principal.size(); j++ ) {
543
        prName = (String)principal.elementAt(j);
544
        pstmt.setString(2, prName);
545
        logMetacat.debug("running sql: " + pstmt.toString());
546
        pstmt.execute();
547
      /*    
548
        // check if there are conflict with permission's order
549
        String permOrderOpos = permOrder;
550
        int perm = getPermissions(permission, prName, docid, permOrder);
551
        if (  perm != 0 ) {
552
          if ( permOrder.equals("allowFirst") ) {
553
            permOrderOpos = "denyFirst";
554
          } else if ( permOrder.equals("denyFirst") ) {
555
            permOrderOpos = "allowFirst";
556
          }
557
          throw new SQLException("Permission(s) " + txtValue(perm) + 
558
                    " for \"" + prName + "\" on document #" + docid +
559
                    " has/have been used with \"" + permOrderOpos + "\"");
560
        }
561
      */
562
      }
563
      pstmt.close();
564

  
565
    } catch (SQLException e) {
566
      throw new 
567
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
568
    }
569
    finally
570
    {
571
      pstmt.close();
572
      //return the DBConnection
573
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
574
    }
575
  }
576

  
577
  /* Get permissions with permission order different than @permOrder. */
578
  private int getPermissions(int permission, String principal,
579
                             String docid, String permOrder)
580
          throws SQLException 
581
  {
582
    PreparedStatement pstmt = null;
583
    DBConnection conn = null;
584
    int serialNumber = -1;
585
    try
586
    {
587
      //check out DBConnection
588
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
589
      serialNumber=conn.getCheckOutSerialNumber();
590
      pstmt = conn.prepareStatement(
591
            "SELECT permission FROM xml_access " +
592
            "WHERE docid = ? " +
593
            "AND principal_name = ? " +
594
            "AND perm_order NOT = ?");
595
      pstmt.setString(1, docid);
596
      pstmt.setString(2, principal);
597
      pstmt.setString(3, permOrder);
598
      logMetacat.debug("running sql: " + pstmt.toString());
599
      pstmt.execute();
600
      ResultSet rs = pstmt.getResultSet();
601
      boolean hasRow = rs.next();
602
      int perm = 0;
603
      while ( hasRow ) {
604
        perm = rs.getInt(1);
605
        perm = permission & perm;
606
        if ( perm != 0 ) {
607
          pstmt.close();
608
          return perm;
609
        }
610
        hasRow = rs.next();
611
      }
612
    }//try
613
    catch (SQLException e)
614
    {
615
      throw e;
616
    }
617
    finally
618
    {
619
      try
620
      {
621
        pstmt.close();
622
      }
623
      finally
624
      {
625
        DBConnectionPool.returnDBConnection(conn, serialNumber);
626
      }
627
    }
628
    return 0;
629
  }
630

  
631
    /* Get the int value of READ, WRITE, CHMOD or ALL. */
632
	public static int intValue(String permission) {
633
		int thisPermission = 0;
634
		if (permission.toUpperCase().contains(CHMODSTRING)) {
635
			thisPermission |= CHMOD;
636
		} 
637
		if (permission.toUpperCase().contains(READSTRING)) {
638
			thisPermission |= READ;
639
		} 
640
		if (permission.toUpperCase().contains(WRITESTRING)) {
641
			thisPermission |= WRITE;
642
		} 
643
		if (permission.toUpperCase().contains(ALLSTRING)) {
644
			thisPermission |= ALL;
645
		}
646

  
647
		if (thisPermission == 0) {
648
			return -1;
649
		} else {
650
			return thisPermission;
651
		}
652
	}
653
  
654
  /* Get the text value of READ, WRITE, CHMOD or ALL. */
655
	public static String txtValue(int permission) {
656
		StringBuffer txtPerm = new StringBuffer();
657
		
658
		if ((permission & ALL) == ALL) {
659
			return ALLSTRING;
660
		}		
661
		if ((permission & CHMOD) == CHMOD) {
662
			txtPerm.append(CHMODSTRING);
663
		}
664
		if ((permission & READ) == READ) {
665
			if (txtPerm.length() > 0)
666
				txtPerm.append(",");
667
			txtPerm.append(READSTRING);
668
		}
669
		if ((permission & WRITE) == WRITE) {
670
			if (txtPerm.length() > 0)
671
				txtPerm.append(",");
672
			txtPerm.append(WRITESTRING);
673
		}
674

  
675
		return txtPerm.toString();
676
	}
677

  
678
// /* Get the text value of READ, WRITE or ALL. */
679
//  public static String txtValue ( int permission )
680
//  {
681
//    StringBuffer txtPerm = new StringBuffer();
682
//    if (permission == READ) {
683
//      txtPerm.append("READ");
684
//    } 
685
//    if (permission == WRITE) {
686
//      txtPerm.append("WRITE");
687
//    }
688
//    if (permission == ALL) {
689
//      txtPerm.append("ALL");
690
//    }
691
//
692
//    return txtPerm.toString();
693
//  }
694

  
695
  /**
696
    * Get Access Control List information for document from db connetion.
697
    * User or Group should have permissions for reading
698
    * access control information for a document specified by @docid.
699
    * @param docid document identifier which acl info to get
700
    * @param user name of user connected to Metacat system
701
    * @param groups names of user's groups to which user belongs
702
    */
703
  public String getACL(String docid, String user, String[] groups) 
704
          throws SQLException, Exception
705
  {
706
    StringBuffer output = new StringBuffer();
707
    StringBuffer outTemp = new StringBuffer();
708
    String accDoctype = PropertyService.getProperty("xml.accessdoctype");
709
    String server = PropertyService.getProperty("server.name");
710
    String docurl = "metacat://" + server + "/?docid=" + docid;
711
    String systemID;
712
    boolean isOwned = false;
713
    boolean hasPermission = false;
714
    String publicAcc;
715
    
716
    String acfid = "";
717
    String acfid_prev = "";
718
    String principal;
719
    Vector principalArr = new Vector();
720
    int permission;
721
    int perm_prev = -1;
722
    String permType;
723
    String permOrder = "";
724
    String permOrder_prev = "";
725
    String beginTime = "";
726
    String begin_prev = "";
727
    String endTime = "";
728
    String end_prev = "";
729
    int ticketCount = -1;
730
    int ticket_prev = -1;
731
    DBConnection conn = null;
732
    int serialNumber = -1;
733
    PreparedStatement pstmt = null;
734
    try {
735
      
736
      //check out DBConnection
737
      conn=DBConnectionPool.getDBConnection("AccessControlList.getACL");
738
      serialNumber=conn.getCheckOutSerialNumber();
739
      
740
      isOwned = isOwned(docid, user);
741
      systemID = getSystemID((String)MetacatUtil.
742
                                      getOptionList(accDoctype).elementAt(0));
743
      publicAcc = getPublicAccess(docid);
744
        
745
      output.append("<?xml version=\"1.0\"?>\n");
746
      output.append("<!DOCTYPE acl PUBLIC \"" + accDoctype + "\" \"" +
747
                    systemID + "\">\n");
748
      output.append("<acl authSystem=\"\">\n");
749

  
750
      
751
      pstmt = conn.prepareStatement(
752
              "SELECT distinct accessfileid, principal_name, permission, " +
753
              "perm_type, perm_order, to_char(begin_time,'mm/dd/yyyy'), " +
754
              "to_char(end_time,'mm/dd/yyyy'), ticket_count " +
755
              "FROM xml_access WHERE docid = ? " +
756
              "ORDER BY accessfileid, perm_order, perm_type, permission");
757
      // Bind the values to the query
758
      pstmt.setString(1, docid);
759
      logMetacat.debug("running sql: " + pstmt.toString());
760
      pstmt.execute();
761
      ResultSet rs = pstmt.getResultSet();
762
      boolean hasRows = rs.next();
763
      while (hasRows) {
764

  
765
        acfid = rs.getString(1);
766
        principal = rs.getString(2);
767
        permission = rs.getInt(3);
768
        permType = rs.getString(4);
769
        permOrder = rs.getString(5);
770
        beginTime = rs.getString(6);
771
        endTime = rs.getString(7);
772
        ticketCount = rs.getInt(8);
773

  
774
        // if @docid is not owned by @user, only ACL info from that
775
        // access files to which @user/@groups has "read" permission
776
        // is extracted
777
        if ( !isOwned ) {
778
          if ( !acfid.equals(acfid_prev) ) {
779
            acfid_prev = acfid;
780
            //hasPermission = this.hasPermission("READ",user,groups,acfid);
781
             PermissionController controller = new PermissionController(acfid);
782
             hasPermission = controller.hasPermission(user,groups,
783
                                            AccessControlInterface.READSTRING);
784
          }
785
          if ( !hasPermission ) {
786
            rs.next();
787
            continue;
788
          }
789
        }
790
        
791
        // open <resource> tag
792
        if ( !permOrder.equals(permOrder_prev) ) {
793
          // close </resource> tag if any was opened 
794
          output.append(outTemp.toString());
795
          outTemp = new StringBuffer();
796
          if ( !permOrder_prev.equals("") ) {
797
            output.append("  </resource>\n");
798
          }
799
          output.append("  <resource order=\"" + permOrder + "\" public=\"" +
800
                        publicAcc + "\">\n");
801
          output.append("    <resourceIdentifier>" + docurl + 
802
                        "</resourceIdentifier>\n");
803
          permOrder_prev = permOrder;
804
        }
805
        
806
        // close </allow> or </deny> tag then open new one
807
        if ( permission != perm_prev ||
808
             (endTime == null) && (end_prev != null) ||
809
             (beginTime == null) && (begin_prev != null) ||
810
             endTime != null && !endTime.equals(end_prev)  ||
811
             beginTime != null && !beginTime.equals(begin_prev) ||
812
             ticketCount != ticket_prev )  {
813
          output.append(outTemp.toString());
814
          outTemp = new StringBuffer();
815
          principalArr.removeAllElements();
816
          output.append("    <" + permType + ">\n");
817
        }
818
        
819
        // put all principals here for the same 
820
        // permission, duration and ticket_count
821
        if ( !principalArr.contains(principal) ) {
822
          principalArr.addElement(principal);
823
          output.append("      <principal>" + principal + "</principal>\n");
824
        } 
825
        
826
        // prepare <permission> tags, <duration> and <ticketCount>
827
        // if any to put within <allow> (<deny>) by next cicle
828
        if ( permission != perm_prev || 
829
             (endTime == null) && (end_prev != null) ||
830
             (beginTime == null) && (begin_prev != null) ||
831
             endTime != null && !endTime.equals(end_prev)  ||
832
             beginTime != null && !beginTime.equals(begin_prev) ||
833
             ticketCount != ticket_prev )  {
834
          if ( (permission & READ) == READ ) {
835
            outTemp.append("      <permission>read</permission>\n");
836
          }
837
          if ( (permission & WRITE) == WRITE ) {
838
            outTemp.append("      <permission>write</permission>\n");
839
          }
840
          if ( (permission & ALL) == ALL ) {
841
            outTemp.append("      <permission>all</permission>\n");
842
          }
843
          if ( (beginTime != null) || (endTime != null) ) {
844
            outTemp.append("      <duration>" + beginTime + " " + endTime +
845
                          "</duration>\n");
846
          }
847
          if ( ticketCount > 0 ) {
848
            outTemp.append("      <ticketCount>" + ticketCount + 
849
                          "</ticketCount>\n");
850
          }
851
          outTemp.append("    </" + permType + ">\n");
852
          perm_prev = permission;
853
          ticket_prev = ticketCount;
854
          begin_prev = beginTime;
855
          end_prev = endTime;
856
        }
857
        
858
        hasRows = rs.next();
859
      }
860

  
861
      // close <allow> or <deny> if anything left in outTemp var
862
      output.append(outTemp.toString());
863

  
864
      // If there are no any acl info for @docid accessible by @user/@group,
865
      // extract only the following information
866
      if ( permOrder.equals("") ) {
867
        output.append("  <resource public=\"" + publicAcc + "\">\n");
868
        output.append("    <resourceIdentifier>" + docurl + 
869
                      "</resourceIdentifier>\n");
870
      }
871
      
872
      // always close them
873
      output.append("  </resource>\n");
874
      output.append("</acl>\n");
875
      
876
      pstmt.close();
877

  
878
      return output.toString();
879

  
880
    } catch (SQLException e) {
881
      throw new 
882
      SQLException("AccessControlList.getACL(). " + e.getMessage());
883
    }
884
    finally
885
    {
886
      try
887
      {
888
        pstmt.close();
889
      }
890
      finally
891
      {
892
        DBConnectionPool.returnDBConnection(conn, serialNumber);
893
      }
894
    }
895
  }
896
  
897
  /* Check if @user is owner of @docid from db conn. */
898
  private boolean isOwned(String docid, String user) throws SQLException {
899
    
900
    PreparedStatement pstmt = null;
901
    DBConnection conn = null;
902
    int serialNumber = -1;
903
    try
904
    {
905
      //check out DBConnection
906
      conn=DBConnectionPool.getDBConnection("AccessControlList.isOwned");
907
      serialNumber=conn.getCheckOutSerialNumber();
908
      pstmt = conn.prepareStatement("SELECT 'x' FROM xml_documents " +
909
                                  "WHERE docid = ? " + 
910
                                  "AND user_owner = ?");
911
      pstmt.setString(1, docid);
912
      pstmt.setString(2, user);
913
      pstmt.execute();
914
      ResultSet rs = pstmt.getResultSet();
915
      boolean hasRow = rs.next();
916
      return hasRow;
917
    }
918
    finally
919
    {
920
      try
921
      {
922
        pstmt.close();
923
      }
924
      finally
925
      {
926
        DBConnectionPool.returnDBConnection(conn, serialNumber);
927
      }
928
    }
929
  }
930

  
931
  /* Get the flag for public "read" access for @docid from db conn. */
932
  private String getPublicAccess(String docid) throws SQLException {
933
    
934
    int publicAcc = 0;
935
    PreparedStatement pstmt = null;
936
    DBConnection conn = null;
937
    int serialNumber = -1;
938
    try
939
    {
940
      //check out DBConnection
941
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPublicAcces");
942
      serialNumber=conn.getCheckOutSerialNumber();
943
      pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
944
                                  "WHERE docid = ?");
945
      pstmt.setString(1, docid);
946
      pstmt.execute();
947
      ResultSet rs = pstmt.getResultSet();
948
      boolean hasRow = rs.next();
949
      if ( hasRow ) {
950
        publicAcc = rs.getInt(1);
951
      }
952
    
953
      return (publicAcc == 1) ? "yes" : "no";
954
    }
955
    finally
956
    {
957
      try
958
      {
959
        pstmt.close();
960
      }
961
      finally
962
      {
963
        DBConnectionPool.returnDBConnection(conn, serialNumber);
964
      }
965
    }
966
  }
967

  
968
  /* Get SystemID for @publicID from Metacat DB Catalog. */
969
  private String getSystemID(String publicID) throws SQLException, PropertyNotFoundException {
970

  
971
		String systemID = "";
972
		PreparedStatement pstmt = null;
973
		DBConnection conn = null;
974
		int serialNumber = -1;
975

  
976
		try {
977
			//check out DBConnection
978
			conn = DBConnectionPool.getDBConnection("AccessControlList.getSystemID");
979
			serialNumber = conn.getCheckOutSerialNumber();
980

  
981
			pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog "
982
					+ "WHERE entry_type = 'DTD' " + "AND public_id = ?");
983
			pstmt.setString(1, publicID);
984
			pstmt.execute();
985
			ResultSet rs = pstmt.getResultSet();
986
			boolean hasRow = rs.next();
987
			if (hasRow) {
988
				systemID = rs.getString(1);
989
				// system id may not have server url on front.  Add it if not.
990
				if (!systemID.startsWith("http://")) {
991
					systemID = SystemUtil.getContextURL() + systemID;
992
				}
993
			}
994

  
995
			return systemID;
996
		}//try
997
		finally {
998
			try {
999
				pstmt.close();
1000
			} finally {
1001
				DBConnectionPool.returnDBConnection(conn, serialNumber);
1002
			}
1003
		}//finally
1004
	}
1005
  
1006
  public static void main(String[] args) {
1007
	  System.out.println("text value for CHMOD (" + CHMOD + "): " + txtValue(CHMOD));
1008
	  System.out.println("text value for READ: (" + READ + "): " + txtValue(READ));
1009
	  System.out.println("text value for WRITE: (" + WRITE + "): " + txtValue(WRITE));
1010
	  System.out.println("text value for ALL: (" + ALL + "): " + txtValue(ALL));
1011
	  int chmod_read = CHMOD|READ;
1012
	  System.out.println("text value for CHMOD|READ: (" + chmod_read + "): " + txtValue(CHMOD|READ));
1013
	  int chmod_write = CHMOD|WRITE;
1014
	  System.out.println("text value for CHMOD|WRITE: (" + chmod_write + "): " + txtValue(CHMOD|WRITE));
1015
	  int chmod_all = CHMOD|ALL;
1016
	  System.out.println("text value for CHMOD|ALL: (" + chmod_all + "): " + txtValue(CHMOD|ALL));
1017
	  int read_write = READ|WRITE;
1018
	  System.out.println("text value for READ|WRITE: (" + read_write + "): " + txtValue(READ|WRITE));
1019
	  int read_all = READ|ALL;
1020
	  System.out.println("text value for READ|ALL: (" + read_all + "): " + txtValue(READ|ALL));
1021
	  int write_all = WRITE|ALL;
1022
	  System.out.println("text value for WRITE|ALL: (" + write_all + "): " + txtValue(WRITE|ALL));
1023
	  int chmod_read_write = CHMOD|READ|WRITE;
1024
	  System.out.println("text value for CHMOD|READ|WRITE: (" + chmod_read_write + "): " + txtValue(CHMOD|READ|WRITE));
1025
	  int chmod_read_all = CHMOD|READ|ALL;
1026
	  System.out.println("text value for CHMOD|READ|ALL: (" + chmod_read_all + "): " + txtValue(CHMOD|READ|ALL));
1027
	  int chmod_write_all = CHMOD|WRITE|ALL;
1028
	  System.out.println("text value for CHMOD|WRITE|ALL: (" + chmod_write_all + "): " + txtValue(CHMOD|WRITE|ALL));
1029
	  int read_write_all = READ|WRITE|ALL;
1030
	  System.out.println("text value for READ|WRITE|ALL: (" + read_write_all + "): " + txtValue(READ|WRITE|ALL));
1031
	  int chmod_read_write_all = CHMOD|READ|WRITE|ALL;
1032
	  System.out.println("text value for CHMOD|READ|WRITE|ALL: (" + chmod_read_write_all + "): " + txtValue(CHMOD|READ|WRITE|ALL));
1033
	  System.out.println();
1034
	  System.out.println("int value for GOOBER: " + intValue("GOOBER"));
1035
	  System.out.println("int value for CHANGEPERMISSION: " + intValue("CHANGEPERMISSION"));
1036
	  System.out.println("int value for READ: " + intValue("READ"));
1037
	  System.out.println("int value for WRITE: " + intValue("WRITE"));
1038
	  System.out.println("int value for ALL: " + intValue("ALL"));
1039
	  System.out.println("int value for CHANGEPERMISSION,READ: " + intValue("CHANGEPERMISSION,READ"));
1040
	  System.out.println("int value for CHANGEPERMISSION,WRITE: " + intValue("CHANGEPERMISSION,WRITE"));
1041
	  System.out.println("int value for CHANGEPERMISSION,ALL: " + intValue("CHANGEPERMISSION,ALL"));
1042
	  System.out.println("int value for READ,WRITE: " + intValue("READ,WRITE"));
1043
	  System.out.println("int value for READ,ALL: " + intValue("READ,ALL"));
1044
	  System.out.println("int value for WRITE,ALL: " + intValue("WRITE,ALL"));
1045
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE: " + intValue("CHANGEPERMISSION,READ,WRITE"));
1046
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,READ,ALL"));
1047
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,WRITE,ALL"));
1048
	  System.out.println("int value for READ,WRITE,ALL: " + intValue("READ,WRITE,ALL"));
1049
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE,ALL: " + intValue("CHANGEPERMISSION,READ,WRITE,ALL"));
1050
  }
1051

  
1052
}
1053 0

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

  
28
package edu.ucsb.nceas.metacat;
29

  
30
import java.io.*;
31
import java.sql.*;
32
import java.util.Stack;
33
import java.util.Vector;
34
import java.util.Hashtable;
35
import java.net.URL;
36
import java.net.MalformedURLException;
37
import org.apache.log4j.Logger;
38

  
39
import edu.ucsb.nceas.metacat.database.DBConnection;
40
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
41
import edu.ucsb.nceas.metacat.util.DocumentUtil;
42

  
43

  
44
/** 
45
 * A Class that loads eml-access.xml file containing ACL for a metadata
46
 * document into relational DB. It extends DefaultHandler class to handle
47
 * SAX parsing events when processing the XML stream.
48
 */
49
public class AccessControlForSingleFile implements AccessControlInterface 
50
{
51

  
52
 
53
 
54
  private String docId;
55
  private String principal;
56
  private int    permission;
57
  private String permType;
58
  private String permOrder;
59
  private Logger logMetacat = Logger.getLogger(AccessControlForSingleFile.class);
60

  
61
 
62
  /**
63
   * Construct an instance of the AccessControlForSingleFile class.
64
   * @param myAccessNumber  the docid or docid with dev will be controlled
65
   * @param myprincipal  the principal will have permission
66
   * @param myPermission the permission will be given
67
   * @param myPermType  the permsission type, allow or deny
68
   * @param myPermOrder  the permission order, allowFirst or denyFirst
69
   */
70
  public AccessControlForSingleFile(String myAccessionNumber,
71
                                    String myPrincipalName,
72
                                    String myPermission,
73
                                    String myPermType,
74
                                    String myPermOrder) 
75
                                   throws Exception
76
  {
77
    try
78
    {
79
      //Get rid of dev if myaccessNumber has one;
80
      docId = DocumentUtil.getDocIdFromString(myAccessionNumber);
81
      if (docId == null || docId.equals(""))
82
      {
83
        throw new Exception("Docid couldn't be null");
84
      }
85
      // Check principal
86
      principal = myPrincipalName;
87
      if (principal == null || principal.equals(""))
88
      {
89
        throw new Exception("principal couldn't be null");
90
      }
91
      // get permission value
92
      permission = AccessControlList.intValue(myPermission);
93
      if (permission == -1)
94
      {
95
        throw new Exception("permission "+ myPermission + " is not valid");
96
      }
97
      // check permission type
98
      permType = myPermType;
99
      // if permtype is not allow or deny, throw a exception
100
      if (permType == null
101
          || (!permType.equals(AccessControlInterface.ALLOW)
102
          && !permType.equals(AccessControlInterface.DENY)))
103
      {
104
        throw new Exception("permtype should be "+AccessControlInterface.ALLOW+
105
                            " or " +AccessControlInterface.DENY);
106
      }
107
      // check permission order
108
      permOrder = myPermOrder;
109
      
110
      // If permission order is not allowFirst or denyFirst, default to denyFirst.
111
      if (permOrder == null || !permOrder.equals(AccessControlInterface.DENYFIRST)) {
112
        permOrder = AccessControlInterface.ALLOWFIRST;
113
      }
114
      
115
      //debugMessage
116
      logMetacat.info("docid in AccessControlForSingleFiel: " +
117
                                docId);
118
      logMetacat.info("principal in AccessControlForSingleFiel: " +
119
                                principal);
120
      logMetacat.info("permission in AccessControlForSingleFiel: " +
121
                                permission);
122
      logMetacat.info("permType in AccessControlForSingleFiel: " +
123
                                permType);
124
      logMetacat.info("permOrder in AccessControlForSingleFiel: " +
125
                                permOrder);
126
    }
127
    catch (Exception e)
128
    {
129
      logMetacat.error("Error in construct of AccessControlForSingle" +
130
                               "File for docid: " + docId + " : " + e.getMessage());
131
      throw e;
132
    }
133
  }
134
  
135

  
136
  
137

  
138

  
139
 
140

  
141
  /**
142
   * Method to insert records into xml_access table
143
   */
144
  
145
  public void insertPermissions() throws SQLException 
146
  {
147
    PreparedStatement pstmt = null;
148
    DBConnection conn = null;
149
    int serialNumber = -1;
150
    try
151
    {
152
      //check out DBConnection
153
      conn=DBConnectionPool.getDBConnection
154
                               ("AccessControlForSingleFiel.insertPermissions");
155
      serialNumber=conn.getCheckOutSerialNumber();
156
      pstmt = conn.prepareStatement(
157
              "INSERT INTO xml_access " + 
158
              "(docid, principal_name, permission, perm_type, perm_order " +
159
              ") VALUES (?,?,?,?,?)");
160
     
161
      // Bind the values to the query
162
      pstmt.setString(1, docId);
163
      pstmt.setString(2, principal);
164
      pstmt.setInt(3, permission);
165
      pstmt.setString(4, permType);
166
      pstmt.setString(5, permOrder);
167
      //pstmt.setString(6, AccessControlInterface.ACLID);
168
      pstmt.execute();
169
    }//try
170
    catch (SQLException e)
171
    {
172
      logMetacat.error("Error in AccessControlForSingleFile.insert" +
173
                               "Permissions: " + e.getMessage());
174
      throw e;
175
    }
176
    finally
177
    {
178
      try
179
      {
180
        pstmt.close();
181
      }
182
      finally
183
      {
184
        DBConnectionPool.returnDBConnection(conn, serialNumber);
185
      }
186
    }
187
   
188
  }
189
  
190
  /**
191
   * 
192
   * @return true if the Access Control for this file already exists in the DB
193
   * @throws SQLException
194
   */
195
  public boolean accessControlExists() throws SQLException 
196
  {
197
	  boolean exists = false;
198
    PreparedStatement pstmt = null;
199
    DBConnection conn = null;
200
    int serialNumber = -1;
201
    try
202
    {
203
      //check out DBConnection
204
      conn=DBConnectionPool.getDBConnection
205
                               ("AccessControlForSingleFiel.accessControlExists");
206
      serialNumber=conn.getCheckOutSerialNumber();
207
      pstmt = conn.prepareStatement(
208
              "SELECT * FROM xml_access " + 
209
              "WHERE docid = ? " +
210
              "AND principal_name = ? " +
211
              "AND permission = ? " +
212
              "AND perm_type = ? " +
213
              "AND perm_order =? ");
214
     
215
      // Bind the values to the query
216
      pstmt.setString(1, docId);
217
      pstmt.setString(2, principal);
218
      pstmt.setInt(3, permission);
219
      pstmt.setString(4, permType);
220
      pstmt.setString(5, permOrder);
221
      
222
      pstmt.execute();
223
      ResultSet rs = pstmt.getResultSet();
224
      exists = rs.next();
225
      
226
    }//try
227
    catch (SQLException e)
228
    {
229
      logMetacat.error("Error in AccessControlForSingleFile.accessControlExists: "
230
                               + e.getMessage());
231
      throw e;
232
    }
233
    finally
234
    {
235
      try
236
      {
237
        pstmt.close();
238
      }
239
      finally
240
      {
241
        DBConnectionPool.returnDBConnection(conn, serialNumber);
242
      }
243
    }
244
    
245
    return exists;
246
   
247
  }
248
  
249
  public String getAccessString() {
250
	  StringBuffer sb = new StringBuffer();
251
	  sb.append("<access>");
252
	  
253
		  sb.append("<permOrder>");
254
		  sb.append(this.permOrder);
255
		  sb.append("</permOrder>");
256
		  
257
		  sb.append("<permType>");
258
		  sb.append(this.permType);
259
		  sb.append("</permType>");
260
		  
261
		  sb.append("<permission>");
262
		  sb.append(AccessControlList.txtValue(this.permission));
263
		  sb.append("</permission>");
264
		  
265
		  sb.append("<principal>");
266
		  sb.append(this.principal);
267
		  sb.append("</principal>");
268

  
269
	  sb.append("</access>");
270
	  
271
	  return sb.toString();
272
	  
273
  }
274

  
275

  
276
}
277 0

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

  
28
package edu.ucsb.nceas.metacat;
29

  
30
import java.util.Vector;
31
import org.apache.log4j.Logger;
32
/**
33
 * A Class that represents an XML access rule. It include principal and 
34
 * permission
35
 */
36
public class AccessRule
37
{
38
  private String permissionType = null;
39
  private Vector<String> principal = new Vector<String>();
40
  private int permission = 0;
41
  private Logger logMetacat = Logger.getLogger(AccessRule.class);
42
  
43
  /** Set the permssionType */
44
  public void setPermissionType(String type)
45
  {
46
    permissionType = type;
47
  }
48
  
49
  public String getPermissionType()
50
  {
51
     return permissionType;
52
  }
53
    
54
  /** Set the a principle */
55
  public void addPrincipal(String newPrincipal) 
56
  {
57
    this.principal.addElement(newPrincipal);
58
  }
59

  
60
  /** Get the principle vector */
61
  public Vector<String> getPrincipal() 
62
  {
63
    return principal;
64
  }
65

  
66
  /** 
67
   * Set a permission. 
68
   */
69
  public void setPermission(int myPermission) 
70
  {
71
    permission = myPermission;
72
  }
73
    
74
  /**
75
   * Get permission
76
   */
77
  public int getPermission()
78
  {
79
    return permission;
80
  }
81
  
82
  /**
83
   * Copy a AccessRule to another accessrule object
84
   */
85
  public Object clone()
86
  {
87
    // create a new object
88
    AccessRule newRule = new AccessRule();
89
    // set permissiontype
90
    logMetacat.info("copy permission type: "+
91
                              this.getPermissionType());
92
    newRule.setPermissionType(this.getPermissionType());
93
    // set permission
94
    logMetacat.info("copy permission: "+
95
                              this.getPermission());
96
    newRule.setPermission(this.getPermission());
97
    // walk through all the principals
98
    Vector principalVector = this.getPrincipal();
99
    for (int i=0; i<principalVector.size(); i++)
100
    {
101
      String name = (String)principalVector.elementAt(i);
102
      logMetacat.info("copy principle: "+ name);
103
      // Add this name to newrules
104
      newRule.addPrincipal(name);
105
    }
106
    return newRule;
107
  }
108
  
109
 
110
}//AccessRule
111 0

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff