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
527
      pstmt = connection.prepareStatement(
528 555 bojilova
              "INSERT INTO xml_access " +
529 645 bojilova
              "(docid, principal_name, permission, perm_type, perm_order," +
530 1750 tao
              "ticket_count, accessfileid) VALUES " +
531
              "(?,?,?,?,?,?,?)");
532 1214 tao
      // Increase DBConnection usage count
533
      connection.increaseUsageCount(1);
534 555 bojilova
      // Bind the values to the query
535 802 bojilova
      pstmt.setString(1, docid);
536 570 bojilova
      pstmt.setInt(3, permission);
537
      pstmt.setString(4, permType);
538
      pstmt.setString(5, permOrder);
539 1750 tao
      pstmt.setString(7, aclid);
540 570 bojilova
      if ( ticketCount > 0 ) {
541 2604 tao
        pstmt.setInt(6, ticketCount);
542 570 bojilova
      } else {
543 2604 tao
        pstmt.setInt(6, 0);
544 570 bojilova
      }
545 1214 tao
546
      //incrase usagecount for DBConnection
547
      //conn.increaseUsageCount(1);
548 688 bojilova
      String prName;
549 802 bojilova
      for ( int j = 0; j < principal.size(); j++ ) {
550
        prName = (String)principal.elementAt(j);
551
        pstmt.setString(2, prName);
552 4140 daigle
        logMetacat.debug("running sql: " + pstmt.toString());
553 802 bojilova
        pstmt.execute();
554
      /*
555
        // check if there are conflict with permission's order
556
        String permOrderOpos = permOrder;
557
        int perm = getPermissions(permission, prName, docid, permOrder);
558
        if (  perm != 0 ) {
559
          if ( permOrder.equals("allowFirst") ) {
560
            permOrderOpos = "denyFirst";
561
          } else if ( permOrder.equals("denyFirst") ) {
562
            permOrderOpos = "allowFirst";
563 688 bojilova
          }
564 802 bojilova
          throw new SQLException("Permission(s) " + txtValue(perm) +
565
                    " for \"" + prName + "\" on document #" + docid +
566
                    " has/have been used with \"" + permOrderOpos + "\"");
567 665 bojilova
        }
568 802 bojilova
      */
569 570 bojilova
      }
570 672 bojilova
      pstmt.close();
571 555 bojilova
572 570 bojilova
    } catch (SQLException e) {
573
      throw new
574
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
575 672 bojilova
    }
576 1214 tao
    finally
577
    {
578
      pstmt.close();
579
      //return the DBConnection
580
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
581
    }
582 672 bojilova
  }
583
584 688 bojilova
  /* Get permissions with permission order different than @permOrder. */
585
  private int getPermissions(int permission, String principal,
586
                             String docid, String permOrder)
587
          throws SQLException
588
  {
589 1214 tao
    PreparedStatement pstmt = null;
590
    DBConnection conn = null;
591
    int serialNumber = -1;
592
    try
593
    {
594
      //check out DBConnection
595
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
596
      serialNumber=conn.getCheckOutSerialNumber();
597
      pstmt = conn.prepareStatement(
598 688 bojilova
            "SELECT permission FROM xml_access " +
599 765 bojilova
            "WHERE docid = ? " +
600
            "AND principal_name = ? " +
601
            "AND perm_order NOT = ?");
602 1214 tao
      pstmt.setString(1, docid);
603
      pstmt.setString(2, principal);
604
      pstmt.setString(3, permOrder);
605 4140 daigle
      logMetacat.debug("running sql: " + pstmt.toString());
606 1214 tao
      pstmt.execute();
607
      ResultSet rs = pstmt.getResultSet();
608
      boolean hasRow = rs.next();
609
      int perm = 0;
610
      while ( hasRow ) {
611
        perm = rs.getInt(1);
612
        perm = permission & perm;
613
        if ( perm != 0 ) {
614
          pstmt.close();
615
          return perm;
616
        }
617
        hasRow = rs.next();
618
      }
619
    }//try
620
    catch (SQLException e)
621
    {
622
      throw e;
623
    }
624
    finally
625
    {
626
      try
627
      {
628 1139 tao
        pstmt.close();
629 688 bojilova
      }
630 1214 tao
      finally
631
      {
632
        DBConnectionPool.returnDBConnection(conn, serialNumber);
633
      }
634 688 bojilova
    }
635
    return 0;
636
  }
637
638 4861 daigle
    /* Get the int value of READ, WRITE, CHMOD or ALL. */
639
	public static int intValue(String permission) {
640 5735 berkley
641 5742 berkley
		int thisPermission = 0;
642 5735 berkley
		try
643
		{
644
		    thisPermission = new Integer(permission).intValue();
645 5741 berkley
		    if(thisPermission >= 0 && thisPermission <= 7)
646
		    {
647
		        return thisPermission;
648
		    }
649
		    else
650
		    {
651
		        thisPermission = -1;
652
		    }
653 5735 berkley
		}
654
		catch(Exception e)
655 5741 berkley
		{ //do nothing.  this must be a word
656 5735 berkley
		}
657
658 4861 daigle
		if (permission.toUpperCase().contains(CHMODSTRING)) {
659
			thisPermission |= CHMOD;
660
		}
661
		if (permission.toUpperCase().contains(READSTRING)) {
662
			thisPermission |= READ;
663
		}
664
		if (permission.toUpperCase().contains(WRITESTRING)) {
665
			thisPermission |= WRITE;
666
		}
667
		if (permission.toUpperCase().contains(ALLSTRING)) {
668
			thisPermission |= ALL;
669
		}
670 688 bojilova
671 5741 berkley
		return thisPermission;
672 4861 daigle
	}
673
674
  /* Get the text value of READ, WRITE, CHMOD or ALL. */
675
	public static String txtValue(int permission) {
676
		StringBuffer txtPerm = new StringBuffer();
677
678
		if ((permission & ALL) == ALL) {
679
			return ALLSTRING;
680
		}
681
		if ((permission & CHMOD) == CHMOD) {
682
			txtPerm.append(CHMODSTRING);
683
		}
684
		if ((permission & READ) == READ) {
685
			if (txtPerm.length() > 0)
686
				txtPerm.append(",");
687
			txtPerm.append(READSTRING);
688
		}
689
		if ((permission & WRITE) == WRITE) {
690
			if (txtPerm.length() > 0)
691
				txtPerm.append(",");
692
			txtPerm.append(WRITESTRING);
693
		}
694 688 bojilova
695 4861 daigle
		return txtPerm.toString();
696
	}
697 688 bojilova
698
  /* Get the flag for public "read" access for @docid from db conn. */
699
  private String getPublicAccess(String docid) throws SQLException {
700
701
    int publicAcc = 0;
702 1214 tao
    PreparedStatement pstmt = null;
703
    DBConnection conn = null;
704
    int serialNumber = -1;
705
    try
706
    {
707
      //check out DBConnection
708
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPublicAcces");
709
      serialNumber=conn.getCheckOutSerialNumber();
710
      pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
711 765 bojilova
                                  "WHERE docid = ?");
712 1214 tao
      pstmt.setString(1, docid);
713
      pstmt.execute();
714
      ResultSet rs = pstmt.getResultSet();
715
      boolean hasRow = rs.next();
716
      if ( hasRow ) {
717
        publicAcc = rs.getInt(1);
718
      }
719
720
      return (publicAcc == 1) ? "yes" : "no";
721 1139 tao
    }
722 1214 tao
    finally
723
    {
724
      try
725
      {
726
        pstmt.close();
727
      }
728
      finally
729
      {
730
        DBConnectionPool.returnDBConnection(conn, serialNumber);
731
      }
732
    }
733 688 bojilova
  }
734
735
  /* Get SystemID for @publicID from Metacat DB Catalog. */
736 4080 daigle
  private String getSystemID(String publicID) throws SQLException, PropertyNotFoundException {
737 688 bojilova
738 4080 daigle
		String systemID = "";
739
		PreparedStatement pstmt = null;
740
		DBConnection conn = null;
741
		int serialNumber = -1;
742
743
		try {
744
			//check out DBConnection
745
			conn = DBConnectionPool.getDBConnection("AccessControlList.getSystemID");
746
			serialNumber = conn.getCheckOutSerialNumber();
747
748
			pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog "
749
					+ "WHERE entry_type = 'DTD' " + "AND public_id = ?");
750
			pstmt.setString(1, publicID);
751
			pstmt.execute();
752
			ResultSet rs = pstmt.getResultSet();
753
			boolean hasRow = rs.next();
754
			if (hasRow) {
755
				systemID = rs.getString(1);
756
				// system id may not have server url on front.  Add it if not.
757
				if (!systemID.startsWith("http://")) {
758 4123 daigle
					systemID = SystemUtil.getContextURL() + systemID;
759 4080 daigle
				}
760
			}
761
762
			return systemID;
763
		}//try
764
		finally {
765
			try {
766
				pstmt.close();
767
			} finally {
768
				DBConnectionPool.returnDBConnection(conn, serialNumber);
769
			}
770
		}//finally
771
	}
772 4861 daigle
773
  public static void main(String[] args) {
774
	  System.out.println("text value for CHMOD (" + CHMOD + "): " + txtValue(CHMOD));
775
	  System.out.println("text value for READ: (" + READ + "): " + txtValue(READ));
776
	  System.out.println("text value for WRITE: (" + WRITE + "): " + txtValue(WRITE));
777
	  System.out.println("text value for ALL: (" + ALL + "): " + txtValue(ALL));
778
	  int chmod_read = CHMOD|READ;
779
	  System.out.println("text value for CHMOD|READ: (" + chmod_read + "): " + txtValue(CHMOD|READ));
780
	  int chmod_write = CHMOD|WRITE;
781
	  System.out.println("text value for CHMOD|WRITE: (" + chmod_write + "): " + txtValue(CHMOD|WRITE));
782
	  int chmod_all = CHMOD|ALL;
783
	  System.out.println("text value for CHMOD|ALL: (" + chmod_all + "): " + txtValue(CHMOD|ALL));
784
	  int read_write = READ|WRITE;
785
	  System.out.println("text value for READ|WRITE: (" + read_write + "): " + txtValue(READ|WRITE));
786
	  int read_all = READ|ALL;
787
	  System.out.println("text value for READ|ALL: (" + read_all + "): " + txtValue(READ|ALL));
788
	  int write_all = WRITE|ALL;
789
	  System.out.println("text value for WRITE|ALL: (" + write_all + "): " + txtValue(WRITE|ALL));
790
	  int chmod_read_write = CHMOD|READ|WRITE;
791
	  System.out.println("text value for CHMOD|READ|WRITE: (" + chmod_read_write + "): " + txtValue(CHMOD|READ|WRITE));
792
	  int chmod_read_all = CHMOD|READ|ALL;
793
	  System.out.println("text value for CHMOD|READ|ALL: (" + chmod_read_all + "): " + txtValue(CHMOD|READ|ALL));
794
	  int chmod_write_all = CHMOD|WRITE|ALL;
795
	  System.out.println("text value for CHMOD|WRITE|ALL: (" + chmod_write_all + "): " + txtValue(CHMOD|WRITE|ALL));
796
	  int read_write_all = READ|WRITE|ALL;
797
	  System.out.println("text value for READ|WRITE|ALL: (" + read_write_all + "): " + txtValue(READ|WRITE|ALL));
798
	  int chmod_read_write_all = CHMOD|READ|WRITE|ALL;
799
	  System.out.println("text value for CHMOD|READ|WRITE|ALL: (" + chmod_read_write_all + "): " + txtValue(CHMOD|READ|WRITE|ALL));
800
	  System.out.println();
801
	  System.out.println("int value for GOOBER: " + intValue("GOOBER"));
802
	  System.out.println("int value for CHANGEPERMISSION: " + intValue("CHANGEPERMISSION"));
803
	  System.out.println("int value for READ: " + intValue("READ"));
804
	  System.out.println("int value for WRITE: " + intValue("WRITE"));
805
	  System.out.println("int value for ALL: " + intValue("ALL"));
806
	  System.out.println("int value for CHANGEPERMISSION,READ: " + intValue("CHANGEPERMISSION,READ"));
807
	  System.out.println("int value for CHANGEPERMISSION,WRITE: " + intValue("CHANGEPERMISSION,WRITE"));
808
	  System.out.println("int value for CHANGEPERMISSION,ALL: " + intValue("CHANGEPERMISSION,ALL"));
809
	  System.out.println("int value for READ,WRITE: " + intValue("READ,WRITE"));
810
	  System.out.println("int value for READ,ALL: " + intValue("READ,ALL"));
811
	  System.out.println("int value for WRITE,ALL: " + intValue("WRITE,ALL"));
812
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE: " + intValue("CHANGEPERMISSION,READ,WRITE"));
813
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,READ,ALL"));
814
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,WRITE,ALL"));
815
	  System.out.println("int value for READ,WRITE,ALL: " + intValue("READ,WRITE,ALL"));
816
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE,ALL: " + intValue("CHANGEPERMISSION,READ,WRITE,ALL"));
817
  }
818 4080 daigle
819 555 bojilova
}