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