Project

General

Profile

« Previous | Next » 

Revision 5098

Added by daigle over 14 years ago

change AccessControlForSingleFile to only be instantiated for one file. move ACL methods to AccessControlForSingleFile. Change format of access sections returned to EML 2.1.0.

View differences:

src/edu/ucsb/nceas/metacat/accesscontrol/XMLAccessAccess.java
1 1
/**
2 2
 *  '$RCSfile$'
3
 *    Purpose: A Class that manages database access of scheduled task 
3
 *    Purpose: A Class that manages database access of xml access  
4 4
 *             information.
5 5
 *  Copyright: 2009 Regents of the University of California and the
6 6
 *             National Center for Ecological Analysis and Synthesis
......
259 259
	}
260 260
	
261 261
	/**
262
	 * Add permissions for a given prinicpal on a given document. If the
263
	 * prinicpal already exists, bitwise OR the permission to the existing
262
	 * Add permissions for a given principal on a given document. If the
263
	 * principal already exists, bitwise OR the permission to the existing
264 264
	 * permission and update.
265 265
	 * 
266 266
	 * @param docId
......
310 310
	}
311 311
	
312 312
	/**
313
	 * Insert an xml access record
313
	 * Set permissions for a given document. This means first removing all access control for the
314
	 * document and then adding the given rules.
315
	 * 
314 316
	 * @param docId
315 317
	 *            document id
318
	 * @param xmlAccessList
319
	 *            list of xml access dao objects that hold new access for the document
320
	 */
321
	public void setXMLAccess(String docId, Vector<XMLAccessDAO> xmlAccessList) throws AccessException {
322
		deleteXMLAccessForDoc(docId);
323
		
324
		// if more than one record exists for this principal on this document with the same
325
		// access type / access order combination, call cleanup to combine common access and then
326
		// re-retrieve the access list.
327
		for(XMLAccessDAO xmlAccessDAO : xmlAccessList) {
328
			insertXMLAccess(docId, xmlAccessDAO.getPrincipalName(), xmlAccessDAO.getPermission(), 
329
					xmlAccessDAO.getPermType(), xmlAccessDAO.getPermOrder());
330
		}
331
	}
332
	
333
	/**
334
	 * Insert an xml access record.  It is assumed that the checks have already been made to 
335
	 * make sure the principal does not already have an access record for this document.  If 
336
	 * one does already exist, that record should be updated and this insert not called.
337
	 * 
338
	 * @param docId
339
	 *            document id
316 340
	 * @param principal
317 341
	 *            principal credentials
318 342
	 * @param permission
......
389 413
	}
390 414
	
391 415
	/**
392
	 * Update existing xml access permissions in the db
416
	 * Update existing xml access permissions in the db.  The permission value should be the combined
417
	 * value of pre-existing permissions plus new permissions.
418
	 * 
393 419
	 * @param docId
394 420
	 *            document id
395 421
	 * @param principalName
......
455 481
	}
456 482
	
457 483
	/**
458
	 * Delete xml access.  This modifies the access in the database for a principal 
484
	 * Remove xml access.  This modifies the access in the database for a principal 
459 485
	 * for a given document.  If the provided permission is exactly the same as what 
460
	 * the principal has, the record is removed from the database.
486
	 * the principal has, the record is deleted from the database.
487
	 * 
461 488
	 * @param docId
462 489
	 *            document id
463 490
	 * @param principalName
464 491
	 *            principal credentials
465 492
	 */
466
	private void removeXMLAccessForPrincipal(String docId, String principalName, Long permission) throws AccessException {
493
	public void removeXMLAccessForPrincipal(String docId, String principalName, Long permission) throws AccessException {
467 494
		if (docId == null) {
468 495
			throw new AccessException("XMLAccessAccess.removeXMLAccessForPrincipal - docid is required when " + 
469 496
					"removing XML access");
......
504 531
	}
505 532
	
506 533
	/**
534
	 * Delete xml access.  This removes all access records from the database for a given document
535
	 * 
536
	 * @param docId
537
	 *            document id
538
	 */
539
	private void deleteXMLAccessForDoc(String docId) throws AccessException {
540
		if (docId == null) {
541
			throw new AccessException("XMLAccessAccess.deleteXMLAccessForPrincipal - docid is required when " + 
542
					"deleting XML access record");
543
		}
544
		
545
	    PreparedStatement pstmt = null;
546
		DBConnection conn = null;
547
		int serialNumber = -1;
548
		try {
549
			// check out DBConnection
550
			conn = DBConnectionPool.getDBConnection("XMLAccessAccess.deleteXMLAccessForDoc");
551
			String sql = "DELETE FROM xml_access WHERE docid = ?";
552
			pstmt = conn.prepareStatement(sql);
553

  
554
			// Bind the values to the query
555
			pstmt.setString(1, docId);
556

  
557
			String sqlReport = "XMLAccessAccess.deleteXMLAccessForDoc - SQL: " + sql;
558
			sqlReport += " [" + docId + "]";
559
			
560
			logMetacat.info(sqlReport);
561

  
562
			pstmt.execute();
563
		} catch (SQLException sqle) {
564
			throw new AccessException("XMLAccessAccess.deleteXMLAccessForDoc - SQL error when deleting"
565
					+ "xml access permissions for doc id: " + docId + ":" + sqle.getMessage());
566
		} finally {
567
			try {
568
				if (pstmt != null) {
569
					pstmt.close();
570
				}
571
			} catch (SQLException sqle) {
572
				logMetacat.error("XMLAccessAccess.deleteXMLAccessForDoc - SQL error when closing prepared " + 
573
						"statement after deleting xml access permissions for doc id: " + ":" + sqle.getMessage());
574
			} finally {
575
				DBConnectionPool.returnDBConnection(conn, serialNumber);
576
			}
577
		}	   
578
	}
579
	
580
	/**
507 581
	 * Delete xml access.  This removes all access records from the database for a principal 
508 582
	 * for a given document
583
	 * 
509 584
	 * @param docId
510 585
	 *            document id
511 586
	 * @param principal
......
628 703
		}
629 704
	   
630 705
	}
631
	
706

  
707
	/**
708
	 * Make sure that only one record exists per principal/permType/document. If
709
	 * more than one record exists, delete the existing records, consolidate the
710
	 * permissions insert the new record.
711
	 * 
712
	 * @param xmlAccessList
713
	 * @throws AccessException
714
	 */
632 715
	private void cleanupXMLAccessForPrincipal(Vector<XMLAccessDAO> xmlAccessList) throws AccessException{
633 716
		
634
		long permissionMask = 0;
717
		int numAllowRecords = 0;
718
		int numDenyRecords = 0;
719
		long allowPermissionMask = 0;
720
		long denyPermissionMask = 0;
635 721
		String docId = null;
636 722
		String principalName = null;
637 723
		String permType = null;
638 724
		String permOrder = null;
639 725
	
640
		if (xmlAccessList.size() == 1) {
641
			return;
642
		}
643 726
		
644 727
		// iterate through the list of access dao objects and bttwise or the permissions.  Most
645 728
		// of this is just doing some error checking to make sure each record is valid.
......
689 772
							"principalName " + principalName + ". Database intervention required ");
690 773
				}
691 774
			}
692
			permissionMask |= xmlAccessDAO.getPermission();
775
			if (permType.equals(AccessControlInterface.ALLOW)) {
776
				numAllowRecords++;
777
				allowPermissionMask |= xmlAccessDAO.getPermission();
778
			} else if (permType.equals(AccessControlInterface.DENY)) {
779
				numDenyRecords++;
780
				denyPermissionMask |= xmlAccessDAO.getPermission();
781
			}
693 782
		}
694 783
		
695
		// remove all records for this user on this doc with this perm type and perm order
696
		// then insert a single record 
697
		deleteXMLAccessForPrincipal(docId, principalName, permType, permOrder);
698
		insertXMLAccess(docId, principalName, permissionMask, permType, permOrder);
784
		// if there was more than one allow record, remove all allow records for this user on this doc 
785
		// with this perm type and perm order then insert a single record 
786
		if (numAllowRecords > 1) {
787
			deleteXMLAccessForPrincipal(docId, principalName, AccessControlInterface.ALLOW, permOrder);
788
			insertXMLAccess(docId, principalName, allowPermissionMask, AccessControlInterface.ALLOW, permOrder);
789
		}
790
		// if there was more than one deny record, remove all deny records for this user on this doc 
791
		// with this perm type and perm order then insert a single record 
792
		if (numDenyRecords > 1) {
793
			deleteXMLAccessForPrincipal(docId, principalName, AccessControlInterface.DENY, permOrder);
794
			insertXMLAccess(docId, principalName, denyPermissionMask, AccessControlInterface.DENY, permOrder);
795
		}
699 796
	}
700 797
	
798
	/**
799
	 * 
800
	 * @param xmlAccessList
801
	 * @throws PermOrderException
802
	 */
701 803
	private void validateDocXMLAccessList(Vector<XMLAccessDAO> xmlAccessList) throws PermOrderException {
702 804
		String permOrder = null;
703 805
		for(XMLAccessDAO xmlAccessDAO : xmlAccessList) {
......
769 871
					". Database intervention required ");
770 872
		}	
771 873
	}
772

  
773
	/**
774
	 * Check if the given list of XML access DAOs has redundant access.  This occurs if there is 
775
	 * more than one instance of any combination of access type and access order.  Note that we
776
	 * assume that the list contains access records for one principal on one document.
777
	 * @param xmlAccessList
778
	 * @return
779
	 * @throws AccessException
780
	 */
781
	private boolean hasRedundantPrincipalAccess(Vector<XMLAccessDAO> xmlAccessList) throws AccessException {
782
		
783
		// These will hold counts of all combinations of access DAOs with different permission
784
		// orders and permission types.  
785
		int allowFirstAllows = 0;
786
		int allowFirstDenys = 0;
787
		int denyFirstAllows = 0;
788
		int denyFirstDenys = 0;
789
		
790
		for(XMLAccessDAO xmlAccessDAO : xmlAccessList) {
791
			if (xmlAccessDAO.getPermOrder().equals(AccessControlInterface.ALLOWFIRST)) {
792
				if (xmlAccessDAO.getPermType().equals(AccessControlInterface.ALLOW)) {
793
					allowFirstAllows++;
794
				} else if (xmlAccessDAO.getPermType().equals(AccessControlInterface.DENY)) {
795
					allowFirstDenys++;
796
				} else {
797
					throw new AccessException("XMLAccessAccess.validatePrincipalXMLAccessList - " + 
798
						"Invalid permission type: "+ xmlAccessDAO.getPermType() + " for document " + 
799
						xmlAccessDAO.getDocId() + ". Database intervention required ");
800
				}
801
			} else if (xmlAccessDAO.getPermOrder().equals(AccessControlInterface.DENYFIRST)) {
802
				if (xmlAccessDAO.getPermType().equals(AccessControlInterface.ALLOW)) {
803
					denyFirstAllows++;
804
				} else if (xmlAccessDAO.getPermType().equals(AccessControlInterface.DENY)) {
805
					denyFirstDenys++;
806
				} else {
807
					throw new AccessException("XMLAccessAccess.validatePrincipalXMLAccessList - " + 
808
						"Invalid permission type: " + xmlAccessDAO.getPermType() + " for document "+ 
809
						xmlAccessDAO.getDocId() + ". Database intervention required ");
810
				}
811
			}
812
		}
813
		return (allowFirstAllows > 1) || (allowFirstDenys > 1) || (denyFirstAllows > 1)
814
				|| (denyFirstDenys > 1);
815
	}
816 874
	
817 875
	/**
818 876
	 * Populate a job data object with the current row in a resultset
src/edu/ucsb/nceas/metacat/accesscontrol/XMLAccessDAO.java
57 57
	}
58 58
	
59 59
	public void setDocId(String docId) {
60
		_docId = docId;
60
		if (docId != null && docId.equals("")) {
61
			docId = null;
62
		} else {
63
			_docId = docId;
64
		}
61 65
	}
62 66

  
63 67
	public String getAccessFileId() {
......
65 69
	}
66 70
	
67 71
	public void setAccessFileId(String accessFileId) {
68
		_accessFileId = accessFileId;
72
		if(accessFileId != null && accessFileId.equals("")) {
73
			_accessFileId = null;
74
		} else {
75
			_accessFileId = accessFileId;
76
		}
69 77
	}
70 78
	
71 79
	public String getPrincipalName() {
......
73 81
	}
74 82
	
75 83
	public void setPrincipalName(String principalName) {
76
		_principalName = principalName;
84
		if (principalName != null && principalName.equals("")) {
85
			_principalName = null;
86
		} else {
87
			_principalName = principalName;
88
		}
77 89
	}
78 90
	
79 91
	public Long getPermission() {
......
89 101
	}
90 102
	
91 103
	public void setPermType(String permType) {
92
		_permType = permType;
104
		if (permType != null && permType.equals("")) {
105
			_permType = null;
106
		} else {
107
			_permType = permType;
108
		}
93 109
	}
94 110
	
95 111
	public String getPermOrder() {
......
97 113
	}
98 114
	
99 115
	public void setPermOrder(String permOrder) {
100
		_permOrder = permOrder;
116
		if (permOrder != null && permOrder.equals("")) {
117
			_permOrder = null;
118
		} else {
119
			_permOrder = permOrder;
120
		}
101 121
	}
102 122
	
103 123
	public Date getBeginTime() {
......
129 149
	}
130 150
	
131 151
	public void setSubTreeId(String subTreeId) {
132
		_subTreeId = subTreeId;
152
		if (subTreeId != null && subTreeId.equals("")) {
153
			_subTreeId = null;
154
		} else {
155
			_subTreeId = subTreeId;
156
		}
133 157
	}
134 158
	
135 159
	public String getStartNodeId() {
......
137 161
	}
138 162
	
139 163
	public void setStartNodeId(String startNodeId) {
140
		_startNodeId = startNodeId;
164
		if (startNodeId != null && startNodeId.equals("")) {
165
			_startNodeId = null;
166
		} else {
167
			_startNodeId = startNodeId;
168
		}
141 169
	}
142 170
	
143 171
	public String getEndNodeId() {
......
145 173
	}
146 174
	
147 175
	public void setEndNodeId(String endNodeId) {
148
		_endNodeId = endNodeId;
176
		if (endNodeId != null && endNodeId.equals("")) {
177
			endNodeId = null;
178
		} else {
179
			_endNodeId = endNodeId;
180
		}
149 181
	}
150 182

  
151 183
}
src/edu/ucsb/nceas/metacat/accesscontrol/AccessControlForSingleFile.java
27 27

  
28 28
package edu.ucsb.nceas.metacat.accesscontrol;
29 29

  
30
import java.sql.*;
30
import java.io.IOException;
31
import java.io.StringReader;
32
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34
import java.sql.SQLException;
35
import java.util.Vector;
31 36

  
32 37
import org.apache.log4j.Logger;
38
import org.xml.sax.ContentHandler;
39
import org.xml.sax.ErrorHandler;
40
import org.xml.sax.InputSource;
41
import org.xml.sax.SAXException;
42
import org.xml.sax.XMLReader;
43
import org.xml.sax.helpers.XMLReaderFactory;
33 44

  
45
import edu.ucsb.nceas.metacat.DocInfoHandler;
46
import edu.ucsb.nceas.metacat.DocumentImpl;
47
import edu.ucsb.nceas.metacat.McdbException;
48
import edu.ucsb.nceas.metacat.PermissionController;
34 49
import edu.ucsb.nceas.metacat.database.DBConnection;
35 50
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
51
import edu.ucsb.nceas.metacat.properties.PropertyService;
36 52
import edu.ucsb.nceas.metacat.shared.AccessException;
37 53
import edu.ucsb.nceas.metacat.util.DocumentUtil;
54
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
38 55

  
39 56

  
40 57
/** 
......
45 62
public class AccessControlForSingleFile implements AccessControlInterface 
46 63
{
47 64

  
48
 
49
 
50 65
  private String docId;
51
  private String principal;
52
  private int    permission;
53
  private String permType;
54
  private String permOrder;
55 66
  private Logger logMetacat = Logger.getLogger(AccessControlForSingleFile.class);
56 67

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

  
129 85
  }
130 86
  
87
  	/**
88
	 * Insert a single access record into the database based on access DAO
89
	 * object
90
	 * 
91
	 * @param xmlAccessDAO
92
	 *            dao object holding info to insert
93
	 */
94
	public void insertPermissions(XMLAccessDAO xmlAccessDAO) throws AccessControlException{
95
		insertPermissions(xmlAccessDAO.getPrincipalName(), xmlAccessDAO.getPermission(), 
96
				xmlAccessDAO.getPermType(), xmlAccessDAO.getPermOrder());
97
	}
131 98

  
132
  
133

  
134

  
135
 
136

  
137
  /**
138
   * Method to insert records into xml_access table
139
   */
140
  
141
  public void insertPermissions() throws AccessControlException {
99
	/**
100
	 * Insert a single access record into the database.
101
	 * 
102
	 * @param principalName
103
	 * @param permission
104
	 * @param permType
105
	 * @param permOrder
106
	 * @throws AccessControlException
107
	 */
108
	public void insertPermissions(String principalName, Long permission, String permType, String permOrder) throws AccessControlException {
142 109
		try {
143 110
			// The addXMLAccess method will create the permission record if it does not exist.  
144 111
			// It will bitwise OR to permissions if the principal already has a record for this
145 112
			// doc id.
146 113
			XMLAccessAccess xmlAccessAccess = new XMLAccessAccess();
147
			xmlAccessAccess.addXMLAccess(docId, principal, new Long(permission), permType, permOrder);
114
			xmlAccessAccess.addXMLAccess(docId, principalName, new Long(permission), permType, permOrder);
148 115
		} catch (AccessException ae) {
149 116
			throw new AccessControlException("AccessControlForSingleFile.insertPermissions - "
150 117
					+ "DB access error when inserting permissions: " + ae.getMessage());
151 118
		} 
152 119
	}
153 120
  
154
  /**
121
	/**
122
	 * Replace existing permissions with a given block of permissions for this
123
	 * document.
155 124
	 * 
125
	 * @param accessBlock
126
	 *            the xml access block. This is the same structure as that
127
	 *            returned by the getdocumentinfo action in metacat.
128
	 */
129
	public void insertPermissions(String accessBlock) throws AccessControlException {
130
		try {			
131
			XMLReader parser = null;
132
			DocInfoHandler docInfoHandler = new DocInfoHandler();
133
			ContentHandler chandler = docInfoHandler;
134

  
135
			// Get an instance of the parser
136
			String parserName = PropertyService.getProperty("xml.saxparser");
137
			parser = XMLReaderFactory.createXMLReader(parserName);
138

  
139
			// Turn off validation
140
			parser.setFeature("http://xml.org/sax/features/validation", false);
141
			parser.setContentHandler((ContentHandler)chandler);
142
			parser.setErrorHandler((ErrorHandler)chandler);
143

  
144
			parser.parse(new InputSource(new StringReader(accessBlock)));
145
			
146
	        Vector<XMLAccessDAO> accessControlList = docInfoHandler.getAccessControlList();
147
	        if (accessControlList != null) {
148
	        	for (XMLAccessDAO xmlAccessDAO : accessControlList) {
149
        			insertPermissions(xmlAccessDAO);
150
					logMetacat.debug("AccessControlForSingleFile.insertPermissions - document " + docId
151
							+ " permissions added to DB");
152
	            }
153
	        }
154
		} catch (PropertyNotFoundException pnfe) {
155
			throw new AccessControlException("AccessControlForSingleFile.insertPermissions - "
156
					+ "property error when inserting permissions: " + pnfe.getMessage());
157
		} catch (SAXException se) {
158
			throw new AccessControlException("AccessControlForSingleFile.insertPermissions - "
159
					+ "SAX error when inserting permissions: " + se.getMessage());
160
		} catch(IOException ioe) {
161
			throw new AccessControlException("AccessControlForSingleFile.insertPermissions - "
162
					+ "I/O error when inserting permissions: " + ioe.getMessage());
163
		}
164
	}
165
  
166
	/**
167
	 * 
156 168
	 * @return true if the Access Control for this file already exists in the DB
157 169
	 * @throws SQLException
158 170
	 */
159
  public boolean accessControlExists() throws SQLException 
160
  {
161
	  boolean exists = false;
162
    PreparedStatement pstmt = null;
163
    DBConnection conn = null;
164
    int serialNumber = -1;
165
    try
166
    {
167
      //check out DBConnection
168
      conn=DBConnectionPool.getDBConnection
171
	public boolean accessControlExists(XMLAccessDAO xmlAccessDAO) throws AccessControlException {
172
		boolean exists = false;
173
		PreparedStatement pstmt = null;
174
		DBConnection conn = null;
175
		int serialNumber = -1;
176
		try {
177
			//check out DBConnection
178
			conn=DBConnectionPool.getDBConnection
169 179
                               ("AccessControlForSingleFiel.accessControlExists");
170
      serialNumber=conn.getCheckOutSerialNumber();
171
      pstmt = conn.prepareStatement(
172
              "SELECT * FROM xml_access " + 
173
              "WHERE docid = ? " +
174
              "AND principal_name = ? " +
175
              "AND permission = ? " +
176
              "AND perm_type = ? " +
177
              "AND perm_order =? ");
180
			serialNumber=conn.getCheckOutSerialNumber();
181
			pstmt = conn.prepareStatement(
182
				"SELECT * FROM xml_access " + 
183
				"WHERE docid = ? " +
184
				"AND principal_name = ? " +
185
				"AND permission = ? " +
186
				"AND perm_type = ? " +
187
				"AND perm_order =? ");
178 188
     
179
      // Bind the values to the query
180
      pstmt.setString(1, docId);
181
      pstmt.setString(2, principal);
182
      pstmt.setInt(3, permission);
183
      pstmt.setString(4, permType);
184
      pstmt.setString(5, permOrder);
189
			// Bind the values to the query
190
			pstmt.setString(1, docId);
191
			pstmt.setString(2, xmlAccessDAO.getPrincipalName());
192
			pstmt.setLong(3, xmlAccessDAO.getPermission());
193
			pstmt.setString(4, xmlAccessDAO.getPermType());
194
			pstmt.setString(5, xmlAccessDAO.getPermOrder());
185 195
      
186
      pstmt.execute();
187
      ResultSet rs = pstmt.getResultSet();
188
      exists = rs.next();
196
			pstmt.execute();
197
			ResultSet rs = pstmt.getResultSet();
198
			exists = rs.next();
189 199
      
190
    }//try
191
    catch (SQLException e)
192
    {
193
      logMetacat.error("Error in AccessControlForSingleFile.accessControlExists: "
194
                               + e.getMessage());
195
      throw e;
196
    }
197
    finally
198
    {
199
      try
200
      {
201
        pstmt.close();
202
      }
203
      finally
204
      {
205
        DBConnectionPool.returnDBConnection(conn, serialNumber);
206
      }
207
    }
200
		} catch (SQLException sqle){
201
			throw new AccessControlException("AccessControlForSingleFile.accessControlExists - SQL error when " +  
202
					"checking if access control exists: " + sqle.getMessage());
203
		} finally {
204
			try {
205
				if(pstmt != null) {
206
					pstmt.close();
207
				}
208
			} catch (SQLException sqle) {
209
				logMetacat.error("AccessControlForSingleFile.accessControlExists - Could not close " + 
210
						"prepared statement: " +sqle.getMessage());
211
			} finally {
212
				DBConnectionPool.returnDBConnection(conn, serialNumber);
213
			}
214
		}
208 215
    
209
    return exists;
210
   
211
  }
216
		return exists;  
217
	}
212 218
  
213
  public String getAccessString() {
214
	  StringBuffer sb = new StringBuffer();
215
	  sb.append("<access>");
216
	  
217
		  sb.append("<permOrder>");
218
		  sb.append(this.permOrder);
219
		  sb.append("</permOrder>");
220
		  
221
		  sb.append("<permType>");
222
		  sb.append(this.permType);
223
		  sb.append("</permType>");
224
		  
225
		  sb.append("<permission>");
226
		  sb.append(AccessControlList.txtValue(this.permission));
227
		  sb.append("</permission>");
228
		  
229
		  sb.append("<principal>");
230
		  sb.append(this.principal);
231
		  sb.append("</principal>");
219
	/**
220
	 * Get Access Control List information for document from db connetion. User
221
	 * or Group should have permissions for reading access control information
222
	 * for a document specified by
223
	 * 
224
	 * @docid.
225
	 * @param docid
226
	 *            document identifier which acl info to get
227
	 * @param user
228
	 *            name of user connected to Metacat system
229
	 * @param groups
230
	 *            names of user's groups to which user belongs
231
	 */
232
	public String getACL(String user, String[] groups, boolean emlCompliant)
233
			throws AccessControlException {
234
		StringBuffer output = new StringBuffer();
235
		boolean hasPermission = false;
232 236

  
233
	  sb.append("</access>");
234
	  
235
	  return sb.toString();
236
	  
237
  }
237
		try {
238
			// Get a list of all access dao objects for this docid
239
			XMLAccessAccess xmlAccessAccess = new XMLAccessAccess();
240
			Vector<XMLAccessDAO> xmlAccessDAOList = xmlAccessAccess.getXMLAccessForDoc(docId);
241
    
242
			hasPermission = isOwned(docId, user);
243
			if (!hasPermission) {
244
				PermissionController controller = new PermissionController(docId);
245
				hasPermission = 
246
					controller.hasPermission(user, groups, READSTRING);
247
			}
238 248

  
249
			if (hasPermission) {
250
				output.append(getAccessString(xmlAccessDAOList, emlCompliant));
251
			}
239 252

  
253
			return output.toString();
254

  
255
		} catch (SQLException sqle) {
256
			throw new AccessControlException("AccessControlForSingleFile.getACL() - SQL error when " + 
257
					"getting ACL: " + sqle.getMessage());
258
		} catch (AccessException ae) {
259
			throw new AccessControlException("AccessControlForSingleFile.getACL() - DB access error when " + 
260
					"getting ACL: " + ae.getMessage());
261
		} catch (McdbException mcdb) {
262
			throw new AccessControlException("AccessControlForSingleFile.getACL() - MCDB error when " + 
263
					"getting ACL: " + mcdb.getMessage());
264
		}
265
	}
266
	
267
	public String getAccessString() throws AccessControlException {
268
		Vector<XMLAccessDAO> xmlAccessDAOList = null;
269
		
270
		try {
271
			// Get a list of all access dao objects for this docid
272
			XMLAccessAccess xmlAccessAccess = new XMLAccessAccess();
273
			xmlAccessDAOList = xmlAccessAccess.getXMLAccessForDoc(docId);
274
		} catch (AccessException ae) {
275
				throw new AccessControlException("AccessControlForSingleFile.getAccessString() - DB access error when " + 
276
						"getting access string: " + ae.getMessage());
277
		} 
278
		
279
		return getAccessString(xmlAccessDAOList, false);
280
	}
281
	
282
	public String getAccessString(Vector<XMLAccessDAO> xmlAccessDAOList, boolean emlCompliant) throws AccessControlException {
283
			
284
		StringBuffer output = new StringBuffer();
285
		StringBuffer tmpOutput = new StringBuffer();
286
		StringBuffer allowOutput = new StringBuffer();
287
		StringBuffer denyOutput = new StringBuffer();
288
		
289
		String principal = null;
290
		int permission = -1;
291
		String permOrder = ALLOWFIRST;
292
		String permType = null;
293
		
294
		// We assume that all the records will have the same permission order, so we can just
295
		// grab the perm order from the first one.
296
		if (xmlAccessDAOList.size() > 0) {
297
			permOrder = xmlAccessDAOList.get(0).getPermOrder();
298
		}
299
		
300
		if (emlCompliant) {
301
			output.append("<?xml version=\"1.0\"?>\n<acc:access");
302
		} else {
303
			output.append("<access ");
304
		}
305

  
306
		output.append(" authSystem=\"knb\" order=\"" + permOrder + "\" id=\"" + docId + "\" scope=\"document\"");
307
	
308
		if (emlCompliant) {
309
			output.append(" xmlns:acc=\"" + DocumentImpl.EML2_1_0NAMESPACE + "\"");
310
		}
311
		
312
		output.append(">\n");
313
		
314
		if (xmlAccessDAOList.size() > 0) {
315
			// Since there should only be one permission order allowed per document,
316
			// we can just grab the order off of the first xml access dao object
317
			permOrder = xmlAccessDAOList.get(0).getPermOrder();
318
		}
319
		
320
		for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
321
			principal = xmlAccessDAO.getPrincipalName();
322
			permission = xmlAccessDAO.getPermission().intValue();
323
			permType = xmlAccessDAO.getPermType();
324
			
325
			tmpOutput.append("    <" + permType + ">\n");
326
			tmpOutput.append("      <principal>" + principal + "</principal>\n");
327
	
328
			if ((permission & READ) == READ) {
329
				tmpOutput.append("      <permission>read</permission>\n");
330
			}
331
			if ((permission & WRITE) == WRITE) {
332
				tmpOutput.append("      <permission>write</permission>\n");
333
			}
334
			if ((permission & ALL) == ALL) {
335
				tmpOutput.append("      <permission>all</permission>\n");
336
			}
337
			if ((permission & CHMOD) == CHMOD) {
338
				tmpOutput.append("      <permission>chmod</permission>\n");
339
			}
340

  
341
			tmpOutput.append("    </" + permType + ">\n");
342
			
343
			if (permType.equals(ALLOW)) {
344
				allowOutput.append(tmpOutput);
345
			} else if (permType.equals(DENY)) {
346
				denyOutput.append(tmpOutput);
347
			}
348
			tmpOutput = new StringBuffer();
349
		}
350
		
351
		// This just orders the allow/deny sections based on the permOrder.  Not 
352
		// required, but convenient later when parsing the output.
353
		if (permOrder.equals(ALLOWFIRST)) {
354
			output.append(allowOutput);
355
			output.append(denyOutput);
356
		} else if (permOrder.equals(DENYFIRST)) {
357
			output.append(denyOutput);
358
			output.append(allowOutput);
359
		}
360
		
361
		if (emlCompliant) {
362
			output.append("</acc:access>");
363
		} else {
364
			output.append("</access>");
365
		}
366
					
367
		return output.toString();
368
	}
369
	
370
	/* Check if @user is owner of @docid from db conn. */
371
	private boolean isOwned(String docid, String user) throws SQLException {
372
		PreparedStatement pstmt = null;
373
		DBConnection conn = null;
374
		int serialNumber = -1;
375
		try {
376
			// check out DBConnection
377
			conn = DBConnectionPool.getDBConnection("AccessControlList.isOwned");
378
			serialNumber = conn.getCheckOutSerialNumber();
379
			pstmt = conn.prepareStatement("SELECT 'x' FROM xml_documents "
380
					+ "WHERE docid = ? " + "AND user_owner = ?");
381
			pstmt.setString(1, docid);
382
			pstmt.setString(2, user);
383
			pstmt.execute();
384
			ResultSet rs = pstmt.getResultSet();
385
			boolean hasRow = rs.next();
386
			return hasRow;
387
		} finally {
388
			try {
389
				if (pstmt != null) {
390
					pstmt.close();
391
				}
392
			} finally {
393
				DBConnectionPool.returnDBConnection(conn, serialNumber);
394
			}
395
		}
396
	}
397

  
398

  
399
	
400
// public String getAccessString() throws AccessControlException {
401
// Vector<XMLAccessDAO> xmlAccessDAOList = null;
402
// try {
403
// XMLAccessAccess xmlAccessAccess = new XMLAccessAccess();
404
//		  xmlAccessDAOList = xmlAccessAccess.getXMLAccessForDoc(docId);
405
//	  } catch (AccessException ae) {
406
//		  throw new AccessControlException("AccessControlForSingleFile.getAccessString - error when getting " + 
407
//				  "access DAO list: " + ae.getMessage());
408
//	  }
409
//	  
410
//	  StringBuffer sb = new StringBuffer();
411
//  
412
//	  for (XMLAccessDAO xmlAccessDAO : xmlAccessDAOList) {
413
//		  sb.append("<access>");
414
//		  
415
//		  sb.append("<permOrder>");
416
//		  sb.append(xmlAccessDAO.getPermOrder());
417
//		  sb.append("</permOrder>");
418
//		  
419
//		  sb.append("<permType>");
420
//		  sb.append(xmlAccessDAO.getPermType());
421
//		  sb.append("</permType>");
422
//		  
423
//		  sb.append("<permission>");
424
//		  sb.append(xmlAccessDAO.getPermission());
425
//		  sb.append("</permission>");
426
//		  
427
//		  sb.append("<principal>");
428
//		  sb.append(xmlAccessDAO.getPrincipalName());
429
//		  sb.append("</principal>");
430
//		  
431
//		  sb.append("</access>");
432
//	  }
433
//  
434
//	  return sb.toString();
435
//	  
436
//  }
437

  
438

  
240 439
}
src/edu/ucsb/nceas/metacat/accesscontrol/AccessControlList.java
51 51
import edu.ucsb.nceas.metacat.database.DBConnection;
52 52
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
53 53
import edu.ucsb.nceas.metacat.properties.PropertyService;
54
import edu.ucsb.nceas.metacat.shared.AccessException;
54 55
import edu.ucsb.nceas.metacat.util.MetacatUtil;
55 56
import edu.ucsb.nceas.metacat.util.SystemUtil;
56 57
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
......
90 91
  private int    permission;
91 92
  private String permType;
92 93
  private String permOrder;
93
//  private String publicAcc;
94 94
  private String beginTime;
95 95
  private String endTime;
96 96
  private int    ticketCount;
......
680 680
		return txtPerm.toString();
681 681
	}
682 682

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

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

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

  
770
        acfid = rs.getString(1);
771
        principal = rs.getString(2);
772
        permission = rs.getInt(3);
773
        permType = rs.getString(4);
774
        permOrder = rs.getString(5);
775
        beginTime = rs.getString(6);
776
        endTime = rs.getString(7);
777
        ticketCount = rs.getInt(8);
778

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

  
869
      // close <allow> or <deny> if anything left in outTemp var
870
      output.append(outTemp.toString());
871

  
872
      // If there are no any acl info for @docid accessible by @user/@group,
873
      // extract only the following information
874
      if ( permOrder.equals("") ) {
875
        output.append("  <resource public=\"" + publicAcc + "\">\n");
876
        output.append("    <resourceIdentifier>" + docurl + 
877
                      "</resourceIdentifier>\n");
878
      }
879
      
880
      // always close them
881
      output.append("  </resource>\n");
882
      output.append("</acl>\n");
883
      
884
      pstmt.close();
885

  
886
      return output.toString();
887

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

  
939 683
  /* Get the flag for public "read" access for @docid from db conn. */
940 684
  private String getPublicAccess(String docid) throws SQLException {
941 685
    
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
73 73
import com.oreilly.servlet.multipart.ParamPart;
74 74
import com.oreilly.servlet.multipart.Part;
75 75

  
76
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlException;
76 77
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlForSingleFile;
77 78
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
78 79
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlList;
......
89 90
import edu.ucsb.nceas.metacat.service.ServiceService;
90 91
import edu.ucsb.nceas.metacat.service.SessionService;
91 92
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
93
import edu.ucsb.nceas.metacat.shared.ServiceException;
92 94
import edu.ucsb.nceas.metacat.shared.BaseException;
93 95
import edu.ucsb.nceas.metacat.shared.HandlerException;
94 96
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
95
import edu.ucsb.nceas.metacat.shared.ServiceException;
97
//import edu.ucsb.nceas.metacat.shared.AccessException;
96 98
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
97 99
import edu.ucsb.nceas.metacat.spatial.SpatialQuery;
98 100
import edu.ucsb.nceas.metacat.util.AuthUtil;
......
2722 2724
        }
2723 2725
        
2724 2726
        try {
2725
            
2726
            // get connection from the pool
2727
            dbConn = DBConnectionPool
2728
                    .getDBConnection("MetaCatServlet.handleGetAccessControlAction");
2729
            serialNumber = dbConn.getCheckOutSerialNumber();
2730
            AccessControlList aclobj = new AccessControlList(dbConn);
2731
            String acltext = aclobj.getACL(docid, username, groupnames);
2727
        	AccessControlForSingleFile acfsf = new AccessControlForSingleFile(docid);
2728
            String acltext = acfsf.getACL(username, groupnames, true);
2732 2729
            if (qformat.equals("xml")) {
2733 2730
                response.setContentType("text/xml");
2734 2731
            	out.println(acltext);
......
3508 3505
    private void handleSetAccessAction(PrintWriter out, Hashtable<String, String[]> params,
3509 3506
            String username, HttpServletRequest request, HttpServletResponse response) {
3510 3507
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
3511
        String[] docList = null;
3512
        String[] principalList = null;
3513
        String[] permissionList = null;
3514
        String[] permTypeList = null;
3515
        String[] permOrderList = null;
3516
        String[] qformatList = null;
3508

  
3517 3509
        String permission = null;
3518 3510
        String permType = null;
3519 3511
        String permOrder = null;
......
3523 3515
        String success = null;
3524 3516
        boolean isEmlPkgMember = false;
3525 3517
        
3526
        // Get parameters
3527
        if (params.containsKey("docid")) {
3528
            docList = params.get("docid");
3529
        }
3530
        if (params.containsKey("principal")) {
3531
            principalList = params.get("principal");
3532
        }
3533
        if (params.containsKey("permission")) {
3534
            permissionList = params.get("permission");
3535
            
3536
        }
3537
        if (params.containsKey("permType")) {
3538
            permTypeList = params.get("permType");
3539
            
3540
        }
3541
        if (params.containsKey("permOrder")) {
3542
            permOrderList = params.get("permOrder");
3543
            
3544
        }
3518
        String[] docList = params.get("docid");
3519
        String[] principalList = params.get("principal");
3520
        String[] permissionList = params.get("permission");
3521
        String[] permTypeList = params.get("permType");
3522
        String[] permOrderList = params.get("permOrder");
3523
        String[] qformatList = params.get("qformat");
3524
        String[] accessBlock = params.get("accessBlock");
3545 3525
        
3546
        if (params.containsKey("qformat")) {
3547
            qformatList = params.get("qformat");
3548
            
3526
        if(accessBlock != null) {
3527
        	if (docList == null) {
3528
        		errorList.addElement("MetaCatServlet.handleSetAccessAction - Please check your parameter list, it should look like: "
3529
                    + "?action=setaccess&docid=<doc_id>&accessBlock=<access_section>");
3530
                outputResponse(successList, errorList, out);
3531
                return;
3532
        	}
3533
        	
3534
        	try {
3535
	            AccessControlForSingleFile accessControl = 
3536
	            	new AccessControlForSingleFile(docList[0]);
3537
	            accessControl.insertPermissions(accessBlock[0]);
3538
        	} catch(AccessControlException ace) {
3539
        		errorList.addElement("MetaCatServlet.handleSetAccessAction - access control error when setting " + 
3540
        			"access block: " + ace.getMessage());
3541
        	} 
3542
        	outputResponse(successList, errorList, out);
3543
        	return;
3549 3544
        }
3550 3545
        
3551 3546
        // Make sure the parameter is not null
......
3606 3601
            } catch (Exception e) {
3607 3602
                logMetacat.error("MetaCatServlet.handleSetAccessAction - Error in handleSetAccessAction: "
3608 3603
                        + e.getMessage());
3609
                error = "Error in set access control for document - "
3610
                        + accessionNumber + e.getMessage();
3604
                error = "Error in set access control for document - " + accessionNumber + e.getMessage();
3611 3605
                errorList.addElement(error);
3612 3606
                continue;
3613 3607
            }
3614 3608
            //check if user is the owner. Only owner can do owner
3615 3609
            if (username == null || owner == null || !username.equals(owner)) {
3616
                error = "User - " + username
3617
                        + " does not have permission to set "
3610
                error = "User - " + username + " does not have permission to set "
3618 3611
                        + "access control for docid - " + accessionNumber;
3619 3612
                errorList.addElement(error);
3620 3613
                continue;
......
3626 3619
            if (isEmlPkgMember == false)
3627 3620
                isEmlPkgMember = (DBUtil.findDataSetDocIdForGivenDocument(accessionNumber) != null);
3628 3621
            
3629
            // If docid publicid is BIN data file or other beta4, 6 package
3630
            // document
3631
            // we could not do set access control. Because we don't want
3632
            // inconsistent
3622
            // If docid publicid is BIN data file or other beta4, 6 package document
3623
            // we could not do set access control. Because we don't want inconsistent
3633 3624
            // to its access docuemnt
3634 3625
            if (publicId != null && packageSet != null
3635 3626
                    && packageSet.contains(publicId) && isEmlPkgMember) {
3636
                error = "Could not set access control to document "
3637
                        + accessionNumber
3627
                error = "Could not set access control to document " + accessionNumber
3638 3628
                        + "because it is in a pakcage and it has a access file for it";
3639 3629
                errorList.addElement(error);
3640 3630
                continue;
......
3645 3635
                String principal = principalList[j];
3646 3636
                try {
3647 3637
                    //insert permission
3648
                    AccessControlForSingleFile accessControl = new AccessControlForSingleFile(
3649
                            accessionNumber, principal, permission, permType, permOrder);
3650
                    accessControl.insertPermissions();
3638
                    AccessControlForSingleFile accessControl = 
3639
                    	new AccessControlForSingleFile(accessionNumber);
3640
                    accessControl.insertPermissions(principal, Long.valueOf(permission), permType, permOrder);
3651 3641
                } catch (Exception ee) {
3652 3642
                    logMetacat.error("MetaCatServlet.handleSetAccessAction - Error inserting permission: "
3653 3643
                            + ee.getMessage());
src/edu/ucsb/nceas/metacat/PermissionController.java
55 55
                                                    // access for this docid
56 56
   private Vector subTreeList = new Vector();
57 57

  
58
   private long TOPLEVELSTARTNODEID = 0; //if start node is 0, means it is top
58
   private static final long TOPLEVELSTARTNODEID = 0; //if start node is 0, means it is top
59 59
                                         //level document
60 60

  
61 61
   private static Logger logMetacat = Logger.getLogger(PermissionController.class);
......
663 663

  
664 664
  }//isAllowFirst
665 665

  
666
/**
667
    * Check if the permission order for user at that documents is allowFirst
668
    * @param principals, list of names of principals to check for
669
    * @param docid, document identifier to check for
670
    */
671
  public Vector<AccessControlForSingleFile> getAccessControl()
672
                  throws SQLException, Exception
673
  {
674
	Vector<AccessControlForSingleFile> accessControl = new Vector<AccessControlForSingleFile>();
675
    boolean hasRow;
676
    PreparedStatement pStmt = null;
677
    DBConnection conn = null;
678
    int serialNumber = -1;
679
    String sql = null;
680
    boolean topLever =false;
681
    sql = "SELECT principal_name, permission, perm_type, perm_order FROM xml_access ";
682

  
683
    //TODO, need this?
684
    long startId = 0;
685
    if (startId == TOPLEVELSTARTNODEID)
686
    {
687
      //top level
688
      topLever = true;
689
      sql += "WHERE docid = ? AND startnodeid is NULL";
690
    }
691
    else
692
    {
693
      //sub tree level
694
      sql += "WHERE docid = ? AND startnodeid = ?";
695
    }
696

  
697
    try
698
    {
699
      //check out DBConnection
700
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
701
      serialNumber=conn.getCheckOutSerialNumber();
702

  
703
      //select permission order from database
704
      pStmt = conn.prepareStatement(sql);
705

  
706
        //bind value
707
        pStmt.setString(1, docId);//docid
708

  
709
        // if subtree, we need set subtree id
710
        if (!topLever)
711
        {
712
          pStmt.setLong(2, startId);
713
        }
714

  
715
        pStmt.execute();
716
        ResultSet rs = pStmt.getResultSet();
717
        while (rs.next())
718
        {
719
          //get the permission order from data base
720
          String principalName=rs.getString(1);
721
          String permission=rs.getString(2);
722
          String permType=rs.getString(3);
723
          String permOrder=rs.getString(4);
724
          
725
          //translate to string version
726
          String myPermission = AccessControlList.txtValue(Integer.parseInt(permission));
727
          
728
          //make it into an object
729
          AccessControlForSingleFile acfsf = 
730
        	  new AccessControlForSingleFile(docId, principalName, myPermission, permType, permOrder);
731
          accessControl.add(acfsf);
732
        }
733
        pStmt.close();
734
    }//try
735
    catch (SQLException e)
736
    {
737
      throw e;
738
    }
739
    finally
740
    {
741
      try
742
      {
743
        pStmt.close();
744
      }
745
      finally
746
      {
747
        DBConnectionPool.returnDBConnection(conn, serialNumber);
748
      }
749
    }
750
    
751
    return accessControl;
752

  
753
  }//getPermissions
754

  
755 666
  /**
756 667
    * Check if the users array has allow rules for given users, docid and
757 668
    * permission.
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff