Project

General

Profile

1 555 bojilova
/**
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 669 jones
 *
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 555 bojilova
 */
27
28 5089 daigle
package edu.ucsb.nceas.metacat.accesscontrol;
29 555 bojilova
30 6606 leinfelder
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 555 bojilova
import java.util.Stack;
36
import java.util.Vector;
37
38 4140 daigle
import org.apache.log4j.Logger;
39 555 bojilova
import org.xml.sax.Attributes;
40 598 bojilova
import org.xml.sax.ContentHandler;
41
import org.xml.sax.EntityResolver;
42
import org.xml.sax.ErrorHandler;
43 6606 leinfelder
import org.xml.sax.InputSource;
44 555 bojilova
import org.xml.sax.SAXException;
45
import org.xml.sax.XMLReader;
46 6606 leinfelder
import org.xml.sax.helpers.DefaultHandler;
47 555 bojilova
import org.xml.sax.helpers.XMLReaderFactory;
48
49 5089 daigle
import edu.ucsb.nceas.metacat.BasicNode;
50
import edu.ucsb.nceas.metacat.DBEntityResolver;
51
import edu.ucsb.nceas.metacat.DocumentImpl;
52
import edu.ucsb.nceas.metacat.McdbException;
53 5015 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
54
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
55 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
56 4080 daigle
import edu.ucsb.nceas.metacat.util.SystemUtil;
57
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
58 7475 leinfelder
import edu.ucsb.nceas.utilities.access.AccessControlInterface;
59 4080 daigle
60 555 bojilova
/**
61
 * A Class that loads eml-access.xml file containing ACL for a metadata
62
 * document into relational DB. It extends DefaultHandler class to handle
63
 * SAX parsing events when processing the XML stream.
64
 */
65 1368 tao
public class AccessControlList extends DefaultHandler
66
                               implements AccessControlInterface
67
{
68 555 bojilova
69 1368 tao
70 4861 daigle
//  private static String sysdate = DatabaseService.getDBAdapter().getDateTimeFunction();
71
//  private static String isnull = DatabaseService.getDBAdapter().getIsNULLFunction();
72 961 tao
73 1214 tao
  private DBConnection connection;
74 555 bojilova
  private String parserName;
75
  private Stack elementStack;
76 645 bojilova
  private String server;
77 802 bojilova
  private String sep;
78 961 tao
79 598 bojilova
  private boolean	processingDTD;
80 645 bojilova
  private String  user;
81 802 bojilova
  private String[] groups;
82 638 bojilova
  private String  aclid;
83 802 bojilova
  private int     rev;
84 598 bojilova
  private String 	docname;
85
  private String 	doctype;
86
  private String 	systemid;
87
88 665 bojilova
  private String docurl;
89
  private Vector resourceURL;
90
  private Vector resourceID;
91 660 bojilova
  private Vector principal;
92 570 bojilova
  private int    permission;
93
  private String permType;
94
  private String permOrder;
95
  private String beginTime;
96
  private String endTime;
97
  private int    ticketCount;
98 684 bojilova
  private int    serverCode = 1;
99 802 bojilova
100
  private Vector aclObjects = new Vector();
101 859 berkley
  private boolean instarttag = true;
102
  private String tagName = "";
103 4140 daigle
104
  private static Logger logMetacat = Logger.getLogger(AccessControlList.class);
105 555 bojilova
  /**
106
   * Construct an instance of the AccessControlList class.
107 688 bojilova
   * It is used by the permission check up from DBQuery or DocumentImpl
108
   * and from "getaccesscontrol" action
109 570 bojilova
   *
110 684 bojilova
   * @param conn the JDBC connection where acl info is get
111 570 bojilova
   */
112 1214 tao
  public AccessControlList(DBConnection conn) throws SQLException
113 570 bojilova
  {
114 1214 tao
    this.connection = conn;
115 570 bojilova
  }
116 1214 tao
117 570 bojilova
118 1214 tao
119
120 570 bojilova
  /**
121
   * Construct an instance of the AccessControlList class.
122 555 bojilova
   * It parse acl file and loads acl data into db connection.
123
   *
124
   * @param conn the JDBC connection where acl data are loaded
125 684 bojilova
   * @param aclid the Accession# of the document with the acl data
126 570 bojilova
   * @param acl the acl file containing acl data
127 684 bojilova
   * @param user the user connected to MetaCat servlet and owns the document
128 802 bojilova
   * @param groups the groups to which user belongs
129 684 bojilova
   * @param serverCode the serverid from xml_replication on which this document
130
   *        resides.
131 555 bojilova
   */
132 4080 daigle
  public AccessControlList(DBConnection conn, String aclid, int rev,
133 802 bojilova
                           String user, String[] groups, int serverCode)
134 4080 daigle
                  throws SAXException, IOException, McdbException, PropertyNotFoundException
135 555 bojilova
  {
136 4213 daigle
		String parserName = PropertyService.getProperty("xml.saxparser");
137 4080 daigle
		this.server = SystemUtil.getSecureServerURL();
138 4212 daigle
		this.sep = PropertyService.getProperty("document.accNumSeparator");
139 555 bojilova
140 4080 daigle
		this.connection = conn;
141
		this.parserName = parserName;
142
		this.processingDTD = false;
143
		this.elementStack = new Stack();
144 819 bojilova
145 4080 daigle
		this.user = user;
146
		this.groups = groups;
147
		this.aclid = aclid;
148
		this.resourceURL = new Vector();
149
		this.resourceID = new Vector();
150
		this.principal = new Vector();
151
		this.permission = 0;
152
		this.ticketCount = 0;
153
		// this.publicAcc = null;
154
		this.serverCode = serverCode;
155 555 bojilova
156 4080 daigle
		// read the access file from db connection
157
		DocumentImpl acldoc = new DocumentImpl(aclid + sep + rev);
158
		String acl = acldoc.toString();
159
		this.rev = acldoc.getRev();
160
161
		// Initialize the parse
162
		XMLReader parser = initializeParser();
163
		// parse the access file and write the info to xml_access
164 4497 daigle
		if (acl != null) {
165
			parser.parse(new InputSource(new StringReader(acl)));
166
		} else {
167
			throw new McdbException("Could not retrieve access control list for:  " + aclid + sep + rev);
168
		}
169 4080 daigle
	}
170
171 819 bojilova
// NOT USED
172 4080 daigle
// /**
173
// * Construct an instance of the AccessControlList class.
174 819 bojilova
//   * It parses eml-access file and loads acl data into db connection.
175
//   * It is used from command line execution.
176
//   *
177
//   * @param conn the JDBC connection where acl data are loaded
178
//   * @param docid the Accession# of the document with the acl data
179
//   * @param aclfilename the name of acl file containing acl data
180
//   * @param user the user connected to MetaCat servlet and owns the document
181
//   * @param groups the groups to which user belongs
182
//   */
183
//  public AccessControlList( Connection conn, String aclid, String aclfilename,
184
//                           String user, String[] groups )
185
//                  throws SAXException, IOException, McdbException
186
//  {
187
//    this(conn, aclid, new FileReader(new File(aclfilename).toString()),
188
//         user, groups, 1);
189
//  }
190 638 bojilova
191 660 bojilova
  /* Set up the SAX parser for reading the XML serialized ACL */
192 555 bojilova
  private XMLReader initializeParser() throws SAXException
193
  {
194
    XMLReader parser = null;
195
196
    // Get an instance of the parser
197
    parser = XMLReaderFactory.createXMLReader(parserName);
198
199 598 bojilova
    // Turn off validation
200 638 bojilova
    parser.setFeature("http://xml.org/sax/features/validation", true);
201 598 bojilova
202
    // Set Handlers in the parser
203 555 bojilova
    // Set the ContentHandler to this instance
204 598 bojilova
    parser.setContentHandler((ContentHandler)this);
205 555 bojilova
206 598 bojilova
    // make a DBEntityResolver instance
207
    // Set the EntityReslover to DBEntityResolver instance
208 1214 tao
    EntityResolver eresolver = new DBEntityResolver(connection,this,null);
209 598 bojilova
    parser.setEntityResolver((EntityResolver)eresolver);
210
211 555 bojilova
    // Set the ErrorHandler to this instance
212 598 bojilova
    parser.setErrorHandler((ErrorHandler)this);
213 555 bojilova
214 862 berkley
    return parser;
215 555 bojilova
  }
216
217
  /**
218 688 bojilova
   * Callback method used by the SAX Parser when beginning of the document
219 645 bojilova
   */
220
  public void startDocument() throws SAXException
221
  {
222
    //delete all previously submitted permissions @ relations
223
    //this happens only on UPDATE of the access file
224
    try {
225 819 bojilova
      this.aclObjects = getACLObjects(aclid);
226 802 bojilova
227 819 bojilova
      //delete all permissions for resources related to @aclid if any
228 645 bojilova
      if ( aclid != null ) {
229
        deletePermissionsForRelatedResources(aclid);
230
      }
231
    } catch (SQLException sqle) {
232
      throw new SAXException(sqle);
233
    }
234
  }
235
236
  /**
237 688 bojilova
   * Callback method used by the SAX Parser when the start tag of an
238 555 bojilova
   * element is detected. Used in this context to parse and store
239
   * the acl information in class variables.
240
   */
241
  public void startElement (String uri, String localName,
242
                            String qName, Attributes atts)
243
         throws SAXException
244
  {
245 859 berkley
    instarttag = true;
246
    if(localName.equals("allow"))
247
    {
248
      tagName = "allow";
249
    }
250
    else if(localName.equals("deny"))
251
    {
252
      tagName = "deny";
253
    }
254 555 bojilova
    BasicNode currentNode = new BasicNode(localName);
255
    if (atts != null) {
256
      int len = atts.getLength();
257
      for (int i = 0; i < len; i++) {
258
        currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i));
259
      }
260
    }
261 802 bojilova
    if ( currentNode.getTagName().equals("acl") ) {
262 570 bojilova
      permOrder = currentNode.getAttribute("order");
263 802 bojilova
    //  publicAcc = currentNode.getAttribute("public");
264 570 bojilova
    }
265 555 bojilova
    elementStack.push(currentNode);
266
  }
267
268
  /**
269 688 bojilova
   * Callback method used by the SAX Parser when the text sequences of an
270 555 bojilova
   * xml stream are detected. Used in this context to parse and store
271
   * the acl information in class variables.
272 859 berkley
   */
273 555 bojilova
  public void characters(char ch[], int start, int length)
274
         throws SAXException
275
  {
276 859 berkley
    if(!instarttag)
277
    {
278
      return;
279
    }
280 555 bojilova
    String inputString = new String(ch, start, length);
281 859 berkley
    inputString = inputString.trim();
282 862 berkley
    //System.out.println("==============inputString: " + inputString);
283 555 bojilova
    BasicNode currentNode = (BasicNode)elementStack.peek();
284
    String currentTag = currentNode.getTagName();
285
286 802 bojilova
      if (currentTag.equals("principal")) {
287 645 bojilova
288 802 bojilova
        principal.addElement(inputString);
289 645 bojilova
290 802 bojilova
      } else if (currentTag.equals("permission")) {
291 645 bojilova
292 802 bojilova
        if ( inputString.trim().toUpperCase().equals("READ") ) {
293
          permission = permission | READ;
294
        } else if ( inputString.trim().toUpperCase().equals("WRITE") ) {
295
          permission = permission | WRITE;
296 944 tao
        } else if ( inputString.trim().toUpperCase().equals("CHANGEPERMISSION"))
297
        {
298 862 berkley
          permission = permission | CHMOD;
299 802 bojilova
        } else if ( inputString.trim().toUpperCase().equals("ALL") ) {
300
          permission = permission | ALL;
301 862 berkley
        }/*else{
302 802 bojilova
          throw new SAXException("Unknown permission type: " + inputString);
303 859 berkley
        }*/
304 645 bojilova
305 802 bojilova
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
306
        beginTime = inputString.trim();
307 645 bojilova
308 802 bojilova
      } else if ( currentTag.equals("stopDate") && endTime == null) {
309
        endTime = inputString.trim();
310 645 bojilova
311 802 bojilova
      } else if (currentTag.equals("ticketCount") && ticketCount == 0 ) {
312
        try {
313
          ticketCount = (new Integer(inputString.trim())).intValue();
314
        } catch (NumberFormatException nfe) {
315
          throw new SAXException("Wrong integer format for:" + inputString);
316
        }
317 555 bojilova
      }
318
  }
319
320
  /**
321 688 bojilova
   * Callback method used by the SAX Parser when the end tag of an
322 555 bojilova
   * element is detected. Used in this context to parse and store
323
   * the acl information in class variables.
324
   */
325
  public void endElement (String uri, String localName, String qName)
326
         throws SAXException
327
  {
328 859 berkley
    instarttag = false;
329 688 bojilova
    BasicNode leaving = (BasicNode)elementStack.pop();
330
    String leavingTagName = leaving.getTagName();
331
332 802 bojilova
    if ( leavingTagName.equals("allow") ||
333
         leavingTagName.equals("deny")    ) {
334 570 bojilova
335
      if ( permission > 0 ) {
336 555 bojilova
337 570 bojilova
        // insert into db calculated permission for the list of principals
338
        try {
339 802 bojilova
          // go through the objects in xml_relation about this acl doc
340
          for (int i=0; i < aclObjects.size(); i++) {
341
            // docid of the current object
342
            String docid = (String)aclObjects.elementAt(i);
343 2641 tao
            //DocumentIdentifier docID = new DocumentIdentifier(docid);
344
            //docid = docID.getIdentifier();
345
            // the docid get here has revision number, so we need to
346
            // remove it.
347 4698 daigle
            //docid = MetacatUtil.getDocIdFromAccessionNumber(docid);
348 2641 tao
            //System.out.println("The docid insert is!!!!!!!!!! "+ docid);
349 802 bojilova
            insertPermissions(docid,leavingTagName);
350
          }
351 968 tao
352 1330 tao
          // if acl is not in object list
353 968 tao
          //should insert permission for aclid itself into database
354 1336 tao
          /*if (!aclObjects.contains(aclid))
355 1330 tao
          {
356
            DocumentIdentifier aclIdItself = new DocumentIdentifier(aclid);
357
            String aclIdString = aclIdItself.getIdentifier();
358
            insertPermissions(aclIdString,leavingTagName);
359 1336 tao
          }*/
360 968 tao
361 802 bojilova
362 570 bojilova
        } catch (SQLException sqle) {
363
          throw new SAXException(sqle);
364 802 bojilova
        } catch (Exception e) {
365
          throw new SAXException(e);
366 570 bojilova
        }
367
      }
368
369 688 bojilova
      // reset the allow/deny permission
370 660 bojilova
      principal = new Vector();
371 555 bojilova
      permission = 0;
372 570 bojilova
      beginTime = null;
373
      endTime = null;
374
      ticketCount = 0;
375 555 bojilova
376 570 bojilova
    }
377 555 bojilova
378
  }
379 598 bojilova
380 688 bojilova
  /**
381
    * SAX Handler that receives notification of DOCTYPE. Sets the DTD.
382
    * @param name name of the DTD
383
    * @param publicId Public Identifier of the DTD
384
    * @param systemId System Identifier of the DTD
385
    */
386 598 bojilova
  public void startDTD(String name, String publicId, String systemId)
387
              throws SAXException {
388
    docname = name;
389
    doctype = publicId;
390
    systemid = systemId;
391
  }
392
393
  /**
394 688 bojilova
   * SAX Handler that receives notification of the start of entities.
395
   * @param name name of the entity
396 598 bojilova
   */
397
  public void startEntity(String name) throws SAXException {
398
    if (name.equals("[dtd]")) {
399
      processingDTD = true;
400
    }
401
  }
402
403
  /**
404 688 bojilova
   * SAX Handler that receives notification of the end of entities.
405
   * @param name name of the entity
406 598 bojilova
   */
407
  public void endEntity(String name) throws SAXException {
408
    if (name.equals("[dtd]")) {
409
      processingDTD = false;
410
    }
411
  }
412
413
  /**
414 688 bojilova
   * Get the document name.
415 598 bojilova
   */
416
  public String getDocname() {
417
    return docname;
418
  }
419
420
  /**
421 688 bojilova
   * Get the document processing state.
422 598 bojilova
   */
423
  public boolean processingDTD() {
424
    return processingDTD;
425
  }
426
427 802 bojilova
  /* Get all objects associated with @aclid from db.*/
428
  private Vector getACLObjects(String aclid)
429 638 bojilova
          throws SQLException
430
  {
431 802 bojilova
    Vector aclObjects = new Vector();
432 1214 tao
    DBConnection conn = null;
433
    int serialNumber = -1;
434
    PreparedStatement pstmt = null;
435
    try
436
    {
437
      //get connection from DBConnectionPool
438
      conn=DBConnectionPool.getDBConnection("AccessControlList.getACLObject");
439
      serialNumber=conn.getCheckOutSerialNumber();
440
441
      // delete all acl records for resources related to @aclid if any
442
      pstmt = conn.prepareStatement(
443 802 bojilova
                             "SELECT object FROM xml_relation " +
444 830 jones
                             "WHERE subject = ? ");
445 1214 tao
      pstmt.setString(1,aclid);
446
      pstmt.execute();
447
      ResultSet rs = pstmt.getResultSet();
448
      boolean hasRows = rs.next();
449
      while (hasRows) {
450 2641 tao
        String object = rs.getString(1);
451
        //System.out.println("add acl object into vector !!!!!!!!!!!!!!!!!"+object);
452
        aclObjects.addElement(object);
453 1214 tao
        hasRows = rs.next();
454
      }//whil
455 802 bojilova
    }
456 1214 tao
    catch (SQLException e)
457
    {
458
      throw e;
459
    }
460
    finally
461
    {
462
      try
463
      {
464
        pstmt.close();
465
      }
466
      finally
467
      {
468
        //retrun DBConnection
469
        DBConnectionPool.returnDBConnection(conn,serialNumber);
470
      }
471
    }
472 802 bojilova
473
    return aclObjects;
474 638 bojilova
  }
475
476 802 bojilova
  /* Delete from db all permission for resources related to @aclid if any.*/
477
  private void deletePermissionsForRelatedResources(String aclid)
478 638 bojilova
          throws SQLException
479
  {
480 1214 tao
    //DBConnection conn = null;
481
    //int serialNumber = -1;
482 6606 leinfelder
    PreparedStatement pstmt = null;
483 1214 tao
    try
484
    {
485
      //check out DBConenction
486
      //conn=DBConnectionPool.getDBConnection("AccessControlList.deltePerm");
487
      //serialNumber=conn.getCheckOutSerialNumber();
488 6606 leinfelder
    	String sql = "DELETE FROM xml_access WHERE accessfileid = ?";
489 1214 tao
      // delete all acl records for resources related to @aclid if any
490 6606 leinfelder
      pstmt = connection.prepareStatement(sql);
491
      pstmt.setString(1, aclid);
492 1214 tao
      // Increase DBConnection usage count
493
      connection.increaseUsageCount(1);
494 6606 leinfelder
      logMetacat.debug("running sql: " + pstmt.toString());
495
      pstmt.execute();
496 1214 tao
      //increase usageCount!!!!!!
497
      //conn.increaseUsageCount(1);
498
    }
499
    catch (SQLException e)
500
    {
501
      throw e;
502
    }
503
    finally
504
    {
505 6606 leinfelder
      pstmt.close();
506 1214 tao
      //retrun DBConnection
507
      //DBConnectionPool.returnDBConnection(conn,serialNumber);
508
    }
509 645 bojilova
  }
510
511 1214 tao
  /* Insert into db calculated permission for the list of principals
512
   * The DBConnection it is use is class field. Because we want to keep rollback
513
   * features and it need use same connection
514
  */
515
516 802 bojilova
  private void insertPermissions(String docid, String permType )
517 1214 tao
                                            throws SQLException
518 555 bojilova
  {
519 1214 tao
    PreparedStatement pstmt = null;
520
    //DBConnection conn = null;
521
    //int serialNumber = -1;
522 555 bojilova
    try {
523 1214 tao
      //Check out DBConnection
524
      //conn=DBConnectionPool.getDBConnection("AccessControlList.insertPerm");
525
      //serialNumber=conn.getCheckOutSerialNumber();
526 8173 leinfelder
    	// TODO: look up guid? this is for very old pre-release versions of EML
527
      String guid = docid;
528 1214 tao
      pstmt = connection.prepareStatement(
529 555 bojilova
              "INSERT INTO xml_access " +
530 8173 leinfelder
              "(guid, principal_name, permission, perm_type, perm_order," +
531 1750 tao
              "ticket_count, accessfileid) VALUES " +
532
              "(?,?,?,?,?,?,?)");
533 1214 tao
      // Increase DBConnection usage count
534
      connection.increaseUsageCount(1);
535 555 bojilova
      // Bind the values to the query
536 8173 leinfelder
      pstmt.setString(1, guid);
537 570 bojilova
      pstmt.setInt(3, permission);
538
      pstmt.setString(4, permType);
539
      pstmt.setString(5, permOrder);
540 1750 tao
      pstmt.setString(7, aclid);
541 570 bojilova
      if ( ticketCount > 0 ) {
542 2604 tao
        pstmt.setInt(6, ticketCount);
543 570 bojilova
      } else {
544 2604 tao
        pstmt.setInt(6, 0);
545 570 bojilova
      }
546 1214 tao
547
      //incrase usagecount for DBConnection
548
      //conn.increaseUsageCount(1);
549 688 bojilova
      String prName;
550 802 bojilova
      for ( int j = 0; j < principal.size(); j++ ) {
551
        prName = (String)principal.elementAt(j);
552
        pstmt.setString(2, prName);
553 4140 daigle
        logMetacat.debug("running sql: " + pstmt.toString());
554 802 bojilova
        pstmt.execute();
555
      /*
556
        // check if there are conflict with permission's order
557
        String permOrderOpos = permOrder;
558
        int perm = getPermissions(permission, prName, docid, permOrder);
559
        if (  perm != 0 ) {
560
          if ( permOrder.equals("allowFirst") ) {
561
            permOrderOpos = "denyFirst";
562
          } else if ( permOrder.equals("denyFirst") ) {
563
            permOrderOpos = "allowFirst";
564 688 bojilova
          }
565 802 bojilova
          throw new SQLException("Permission(s) " + txtValue(perm) +
566
                    " for \"" + prName + "\" on document #" + docid +
567
                    " has/have been used with \"" + permOrderOpos + "\"");
568 665 bojilova
        }
569 802 bojilova
      */
570 570 bojilova
      }
571 672 bojilova
      pstmt.close();
572 555 bojilova
573 570 bojilova
    } catch (SQLException e) {
574
      throw new
575
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
576 672 bojilova
    }
577 1214 tao
    finally
578
    {
579
      pstmt.close();
580
      //return the DBConnection
581
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
582
    }
583 672 bojilova
  }
584
585 688 bojilova
  /* Get permissions with permission order different than @permOrder. */
586
  private int getPermissions(int permission, String principal,
587
                             String docid, String permOrder)
588
          throws SQLException
589
  {
590 1214 tao
    PreparedStatement pstmt = null;
591
    DBConnection conn = null;
592
    int serialNumber = -1;
593
    try
594
    {
595
      //check out DBConnection
596
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
597
      serialNumber=conn.getCheckOutSerialNumber();
598
      pstmt = conn.prepareStatement(
599 688 bojilova
            "SELECT permission FROM xml_access " +
600 765 bojilova
            "WHERE docid = ? " +
601
            "AND principal_name = ? " +
602
            "AND perm_order NOT = ?");
603 1214 tao
      pstmt.setString(1, docid);
604
      pstmt.setString(2, principal);
605
      pstmt.setString(3, permOrder);
606 4140 daigle
      logMetacat.debug("running sql: " + pstmt.toString());
607 1214 tao
      pstmt.execute();
608
      ResultSet rs = pstmt.getResultSet();
609
      boolean hasRow = rs.next();
610
      int perm = 0;
611
      while ( hasRow ) {
612
        perm = rs.getInt(1);
613
        perm = permission & perm;
614
        if ( perm != 0 ) {
615
          pstmt.close();
616
          return perm;
617
        }
618
        hasRow = rs.next();
619
      }
620
    }//try
621
    catch (SQLException e)
622
    {
623
      throw e;
624
    }
625
    finally
626
    {
627
      try
628
      {
629 1139 tao
        pstmt.close();
630 688 bojilova
      }
631 1214 tao
      finally
632
      {
633
        DBConnectionPool.returnDBConnection(conn, serialNumber);
634
      }
635 688 bojilova
    }
636
    return 0;
637
  }
638
639 4861 daigle
    /* Get the int value of READ, WRITE, CHMOD or ALL. */
640
	public static int intValue(String permission) {
641 5735 berkley
642 5742 berkley
		int thisPermission = 0;
643 5735 berkley
		try
644
		{
645
		    thisPermission = new Integer(permission).intValue();
646 5741 berkley
		    if(thisPermission >= 0 && thisPermission <= 7)
647
		    {
648
		        return thisPermission;
649
		    }
650
		    else
651
		    {
652
		        thisPermission = -1;
653
		    }
654 5735 berkley
		}
655
		catch(Exception e)
656 5741 berkley
		{ //do nothing.  this must be a word
657 5735 berkley
		}
658
659 4861 daigle
		if (permission.toUpperCase().contains(CHMODSTRING)) {
660
			thisPermission |= CHMOD;
661
		}
662
		if (permission.toUpperCase().contains(READSTRING)) {
663
			thisPermission |= READ;
664
		}
665
		if (permission.toUpperCase().contains(WRITESTRING)) {
666
			thisPermission |= WRITE;
667
		}
668
		if (permission.toUpperCase().contains(ALLSTRING)) {
669
			thisPermission |= ALL;
670
		}
671 688 bojilova
672 5741 berkley
		return thisPermission;
673 4861 daigle
	}
674
675
  /* Get the text value of READ, WRITE, CHMOD or ALL. */
676
	public static String txtValue(int permission) {
677
		StringBuffer txtPerm = new StringBuffer();
678
679
		if ((permission & ALL) == ALL) {
680
			return ALLSTRING;
681
		}
682
		if ((permission & CHMOD) == CHMOD) {
683
			txtPerm.append(CHMODSTRING);
684
		}
685
		if ((permission & READ) == READ) {
686
			if (txtPerm.length() > 0)
687
				txtPerm.append(",");
688
			txtPerm.append(READSTRING);
689
		}
690
		if ((permission & WRITE) == WRITE) {
691
			if (txtPerm.length() > 0)
692
				txtPerm.append(",");
693
			txtPerm.append(WRITESTRING);
694
		}
695 688 bojilova
696 4861 daigle
		return txtPerm.toString();
697
	}
698 688 bojilova
699
  /* Get the flag for public "read" access for @docid from db conn. */
700
  private String getPublicAccess(String docid) throws SQLException {
701
702
    int publicAcc = 0;
703 1214 tao
    PreparedStatement pstmt = null;
704
    DBConnection conn = null;
705
    int serialNumber = -1;
706
    try
707
    {
708
      //check out DBConnection
709
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPublicAcces");
710
      serialNumber=conn.getCheckOutSerialNumber();
711
      pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
712 765 bojilova
                                  "WHERE docid = ?");
713 1214 tao
      pstmt.setString(1, docid);
714
      pstmt.execute();
715
      ResultSet rs = pstmt.getResultSet();
716
      boolean hasRow = rs.next();
717
      if ( hasRow ) {
718
        publicAcc = rs.getInt(1);
719
      }
720
721
      return (publicAcc == 1) ? "yes" : "no";
722 1139 tao
    }
723 1214 tao
    finally
724
    {
725
      try
726
      {
727
        pstmt.close();
728
      }
729
      finally
730
      {
731
        DBConnectionPool.returnDBConnection(conn, serialNumber);
732
      }
733
    }
734 688 bojilova
  }
735
736
  /* Get SystemID for @publicID from Metacat DB Catalog. */
737 4080 daigle
  private String getSystemID(String publicID) throws SQLException, PropertyNotFoundException {
738 688 bojilova
739 4080 daigle
		String systemID = "";
740
		PreparedStatement pstmt = null;
741
		DBConnection conn = null;
742
		int serialNumber = -1;
743
744
		try {
745
			//check out DBConnection
746
			conn = DBConnectionPool.getDBConnection("AccessControlList.getSystemID");
747
			serialNumber = conn.getCheckOutSerialNumber();
748
749
			pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog "
750
					+ "WHERE entry_type = 'DTD' " + "AND public_id = ?");
751
			pstmt.setString(1, publicID);
752
			pstmt.execute();
753
			ResultSet rs = pstmt.getResultSet();
754
			boolean hasRow = rs.next();
755
			if (hasRow) {
756
				systemID = rs.getString(1);
757
				// system id may not have server url on front.  Add it if not.
758
				if (!systemID.startsWith("http://")) {
759 4123 daigle
					systemID = SystemUtil.getContextURL() + systemID;
760 4080 daigle
				}
761
			}
762
763
			return systemID;
764
		}//try
765
		finally {
766
			try {
767
				pstmt.close();
768
			} finally {
769
				DBConnectionPool.returnDBConnection(conn, serialNumber);
770
			}
771
		}//finally
772
	}
773 4861 daigle
774
  public static void main(String[] args) {
775
	  System.out.println("text value for CHMOD (" + CHMOD + "): " + txtValue(CHMOD));
776
	  System.out.println("text value for READ: (" + READ + "): " + txtValue(READ));
777
	  System.out.println("text value for WRITE: (" + WRITE + "): " + txtValue(WRITE));
778
	  System.out.println("text value for ALL: (" + ALL + "): " + txtValue(ALL));
779
	  int chmod_read = CHMOD|READ;
780
	  System.out.println("text value for CHMOD|READ: (" + chmod_read + "): " + txtValue(CHMOD|READ));
781
	  int chmod_write = CHMOD|WRITE;
782
	  System.out.println("text value for CHMOD|WRITE: (" + chmod_write + "): " + txtValue(CHMOD|WRITE));
783
	  int chmod_all = CHMOD|ALL;
784
	  System.out.println("text value for CHMOD|ALL: (" + chmod_all + "): " + txtValue(CHMOD|ALL));
785
	  int read_write = READ|WRITE;
786
	  System.out.println("text value for READ|WRITE: (" + read_write + "): " + txtValue(READ|WRITE));
787
	  int read_all = READ|ALL;
788
	  System.out.println("text value for READ|ALL: (" + read_all + "): " + txtValue(READ|ALL));
789
	  int write_all = WRITE|ALL;
790
	  System.out.println("text value for WRITE|ALL: (" + write_all + "): " + txtValue(WRITE|ALL));
791
	  int chmod_read_write = CHMOD|READ|WRITE;
792
	  System.out.println("text value for CHMOD|READ|WRITE: (" + chmod_read_write + "): " + txtValue(CHMOD|READ|WRITE));
793
	  int chmod_read_all = CHMOD|READ|ALL;
794
	  System.out.println("text value for CHMOD|READ|ALL: (" + chmod_read_all + "): " + txtValue(CHMOD|READ|ALL));
795
	  int chmod_write_all = CHMOD|WRITE|ALL;
796
	  System.out.println("text value for CHMOD|WRITE|ALL: (" + chmod_write_all + "): " + txtValue(CHMOD|WRITE|ALL));
797
	  int read_write_all = READ|WRITE|ALL;
798
	  System.out.println("text value for READ|WRITE|ALL: (" + read_write_all + "): " + txtValue(READ|WRITE|ALL));
799
	  int chmod_read_write_all = CHMOD|READ|WRITE|ALL;
800
	  System.out.println("text value for CHMOD|READ|WRITE|ALL: (" + chmod_read_write_all + "): " + txtValue(CHMOD|READ|WRITE|ALL));
801
	  System.out.println();
802
	  System.out.println("int value for GOOBER: " + intValue("GOOBER"));
803
	  System.out.println("int value for CHANGEPERMISSION: " + intValue("CHANGEPERMISSION"));
804
	  System.out.println("int value for READ: " + intValue("READ"));
805
	  System.out.println("int value for WRITE: " + intValue("WRITE"));
806
	  System.out.println("int value for ALL: " + intValue("ALL"));
807
	  System.out.println("int value for CHANGEPERMISSION,READ: " + intValue("CHANGEPERMISSION,READ"));
808
	  System.out.println("int value for CHANGEPERMISSION,WRITE: " + intValue("CHANGEPERMISSION,WRITE"));
809
	  System.out.println("int value for CHANGEPERMISSION,ALL: " + intValue("CHANGEPERMISSION,ALL"));
810
	  System.out.println("int value for READ,WRITE: " + intValue("READ,WRITE"));
811
	  System.out.println("int value for READ,ALL: " + intValue("READ,ALL"));
812
	  System.out.println("int value for WRITE,ALL: " + intValue("WRITE,ALL"));
813
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE: " + intValue("CHANGEPERMISSION,READ,WRITE"));
814
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,READ,ALL"));
815
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,WRITE,ALL"));
816
	  System.out.println("int value for READ,WRITE,ALL: " + intValue("READ,WRITE,ALL"));
817
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE,ALL: " + intValue("CHANGEPERMISSION,READ,WRITE,ALL"));
818
  }
819 4080 daigle
820 555 bojilova
}