Project

General

Profile

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

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

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

    
38
import org.apache.log4j.Logger;
39
import org.xml.sax.Attributes;
40
import org.xml.sax.ContentHandler;
41
import org.xml.sax.DTDHandler;
42
import org.xml.sax.EntityResolver;
43
import org.xml.sax.ErrorHandler;
44
import org.xml.sax.InputSource;
45
import org.xml.sax.SAXException;
46
import org.xml.sax.XMLReader;
47
import org.xml.sax.ext.LexicalHandler;
48
import org.xml.sax.helpers.DefaultHandler;
49
import org.xml.sax.helpers.XMLReaderFactory;
50

    
51
import edu.ucsb.nceas.metacat.BasicNode;
52
import edu.ucsb.nceas.metacat.DBEntityResolver;
53
import edu.ucsb.nceas.metacat.DBSAXNode;
54
import edu.ucsb.nceas.metacat.DocumentImpl;
55
import edu.ucsb.nceas.metacat.McdbException;
56
import edu.ucsb.nceas.metacat.database.DBConnection;
57
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
58
import edu.ucsb.nceas.metacat.properties.PropertyService;
59
import edu.ucsb.nceas.metacat.util.SystemUtil;
60
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
61
import edu.ucsb.nceas.utilities.access.AccessControlInterface;
62

    
63
/** 
64
 * A Class that loads eml-access.xml file containing ACL for a metadata
65
 * document into relational DB. It extends DefaultHandler class to handle
66
 * SAX parsing events when processing the XML stream.
67
 */
68
public class AccessControlList extends DefaultHandler 
69
                               implements AccessControlInterface, LexicalHandler
70
{
71

    
72
 
73
//  private static String sysdate = DatabaseService.getDBAdapter().getDateTimeFunction();
74
//  private static String isnull = DatabaseService.getDBAdapter().getIsNULLFunction();
75
  
76
  private DBConnection connection;
77
  private String parserName;
78
  private Stack elementStack;
79
  private String server;
80
  private String sep;
81
 
82
  private boolean	processingDTD;
83
  private String  user;
84
  private String[] groups;
85
  private String  aclid;
86
  private int     rev;
87
  private String 	docname;
88
  private String 	doctype;
89
  private String 	systemid;
90

    
91
  private String docurl;
92
  private Vector resourceURL;
93
  private Vector resourceID;
94
  private Vector principal;
95
  private int    permission;
96
  private String permType;
97
  private String permOrder;
98
  private String beginTime;
99
  private String endTime;
100
  private int    ticketCount;
101
  private int    serverCode = 1;
102

    
103
  private Vector aclObjects = new Vector();
104
  private boolean instarttag = true;
105
  private String tagName = "";
106
  
107
  private static Logger logMetacat = Logger.getLogger(AccessControlList.class);
108
  /**
109
   * Construct an instance of the AccessControlList class.
110
   * It is used by the permission check up from DBQuery or DocumentImpl
111
   * and from "getaccesscontrol" action
112
   *
113
   * @param conn the JDBC connection where acl info is get
114
   */
115
  public AccessControlList(DBConnection conn) throws SQLException
116
  {
117
    this.connection = conn;
118
  }
119
  
120

    
121
  
122

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

    
143
		this.connection = conn;
144
		this.parserName = parserName;
145
		this.processingDTD = false;
146
		this.elementStack = new Stack();
147

    
148
		this.user = user;
149
		this.groups = groups;
150
		this.aclid = aclid;
151
		this.resourceURL = new Vector();
152
		this.resourceID = new Vector();
153
		this.principal = new Vector();
154
		this.permission = 0;
155
		this.ticketCount = 0;
156
		// this.publicAcc = null;
157
		this.serverCode = serverCode;
158

    
159
		// read the access file from db connection
160
		DocumentImpl acldoc = new DocumentImpl(aclid + sep + rev);
161
		String acl = acldoc.toString();
162
		this.rev = acldoc.getRev();
163

    
164
		// Initialize the parse
165
		XMLReader parser = initializeParser();
166
		// parse the access file and write the info to xml_access
167
		if (acl != null) {
168
			parser.parse(new InputSource(new StringReader(acl)));
169
		} else {
170
			throw new McdbException("Could not retrieve access control list for:  " + aclid + sep + rev);
171
		}
172
	}
173

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

    
199
    // Get an instance of the parser
200
    parser = XMLReaderFactory.createXMLReader(parserName);
201

    
202
    // Turn off validation
203
    parser.setFeature("http://xml.org/sax/features/validation", true);
204
    parser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
205
      
206
    // Set Handlers in the parser
207
    // Set the ContentHandler to this instance
208
    parser.setContentHandler((ContentHandler)this);
209

    
210
    // make a DBEntityResolver instance
211
    // Set the EntityReslover to DBEntityResolver instance
212
    EntityResolver eresolver = new DBEntityResolver(connection,this,null);
213
    parser.setEntityResolver((EntityResolver)eresolver);
214
    parser.setDTDHandler((DTDHandler)this);
215

    
216
    // Set the ErrorHandler to this instance
217
    parser.setErrorHandler((ErrorHandler)this);
218

    
219
    return parser; 
220
  }
221
  
222
  /**
223
   * Callback method used by the SAX Parser when beginning of the document
224
   */
225
  public void startDocument() throws SAXException 
226
  {
227
    //delete all previously submitted permissions @ relations
228
    //this happens only on UPDATE of the access file
229
    try {
230
      this.aclObjects = getACLObjects(aclid);
231

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

    
274
  /**
275
   * Callback method used by the SAX Parser when the text sequences of an 
276
   * xml stream are detected. Used in this context to parse and store
277
   * the acl information in class variables.
278
   */ 
279
  public void characters(char ch[], int start, int length)
280
         throws SAXException 
281
  {
282
    if(!instarttag)
283
    {
284
      return;
285
    }
286
    String inputString = new String(ch, start, length);
287
    inputString = inputString.trim(); 
288
    //System.out.println("==============inputString: " + inputString);
289
    BasicNode currentNode = (BasicNode)elementStack.peek(); 
290
    String currentTag = currentNode.getTagName();
291

    
292
      if (currentTag.equals("principal")) {
293

    
294
        principal.addElement(inputString);
295

    
296
      } else if (currentTag.equals("permission")) {
297

    
298
        if ( inputString.trim().toUpperCase().equals("READ") ) {
299
          permission = permission | READ;
300
        } else if ( inputString.trim().toUpperCase().equals("WRITE") ) {
301
          permission = permission | WRITE;
302
        } else if ( inputString.trim().toUpperCase().equals("CHANGEPERMISSION")) 
303
        {
304
          permission = permission | CHMOD;
305
        } else if ( inputString.trim().toUpperCase().equals("ALL") ) {
306
          permission = permission | ALL;
307
        }/*else{
308
          throw new SAXException("Unknown permission type: " + inputString);
309
        }*/
310

    
311
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
312
        beginTime = inputString.trim();
313

    
314
      } else if ( currentTag.equals("stopDate") && endTime == null) {
315
        endTime = inputString.trim();
316

    
317
      } else if (currentTag.equals("ticketCount") && ticketCount == 0 ) {
318
        try {
319
          ticketCount = (new Integer(inputString.trim())).intValue();
320
        } catch (NumberFormatException nfe) {
321
          throw new SAXException("Wrong integer format for:" + inputString);
322
        }
323
      }
324
  }
325

    
326
  /**
327
   * Callback method used by the SAX Parser when the end tag of an 
328
   * element is detected. Used in this context to parse and store
329
   * the acl information in class variables.
330
   */
331
  public void endElement (String uri, String localName, String qName)
332
         throws SAXException 
333
  {
334
    instarttag = false;
335
    BasicNode leaving = (BasicNode)elementStack.pop();
336
    String leavingTagName = leaving.getTagName();
337

    
338
    if ( leavingTagName.equals("allow") ||
339
         leavingTagName.equals("deny")    ) {
340
      
341
      if ( permission > 0 ) {
342

    
343
        // insert into db calculated permission for the list of principals
344
        try {
345
          // go through the objects in xml_relation about this acl doc
346
          for (int i=0; i < aclObjects.size(); i++) {
347
            // docid of the current object
348
            String docid = (String)aclObjects.elementAt(i); 
349
            //DocumentIdentifier docID = new DocumentIdentifier(docid);
350
            //docid = docID.getIdentifier();
351
            // the docid get here has revision number, so we need to 
352
            // remove it.
353
            //docid = MetacatUtil.getDocIdFromAccessionNumber(docid);
354
            //System.out.println("The docid insert is!!!!!!!!!! "+ docid);
355
            insertPermissions(docid,leavingTagName);
356
          }
357
          
358
          // if acl is not in object list
359
          //should insert permission for aclid itself into database
360
          /*if (!aclObjects.contains(aclid))
361
          {
362
            DocumentIdentifier aclIdItself = new DocumentIdentifier(aclid);
363
            String aclIdString = aclIdItself.getIdentifier();
364
            insertPermissions(aclIdString,leavingTagName);
365
          }*/
366
          
367

    
368
        } catch (SQLException sqle) {
369
          throw new SAXException(sqle);
370
        } catch (Exception e) {
371
          throw new SAXException(e);
372
        }
373
      }
374

    
375
      // reset the allow/deny permission
376
      principal = new Vector();
377
      permission = 0;
378
      beginTime = null;
379
      endTime = null;
380
      ticketCount = 0;
381
    
382
    }
383

    
384
  }
385

    
386
  /** 
387
    * SAX Handler that receives notification of DOCTYPE. Sets the DTD.
388
    * @param name name of the DTD
389
    * @param publicId Public Identifier of the DTD
390
    * @param systemId System Identifier of the DTD
391
    */
392
  @Override
393
  public void startDTD(String name, String publicId, String systemId) 
394
              throws SAXException {
395
      processingDTD = true;
396
      logMetacat.debug("AccessControlList.startDTD - Setting processingDTD to true");
397
      logMetacat.debug("AccessControlList.startDTD - start DTD");
398
    docname = name;
399
    doctype = publicId;
400
    systemid = systemId;
401
  }
402
  
403
  /**
404
   * SAX Handler that receives notification of end of DTD
405
   */
406
  @Override
407
  public void endDTD() throws SAXException
408
  {
409

    
410
      processingDTD = false;
411
      logMetacat.debug("AccessControlList.endDTD - Setting processingDTD to false");
412
      logMetacat.debug("AccessControlList.endDTD - end DTD");
413
  }
414

    
415
  /** 
416
   * SAX Handler that receives notification of the start of entities.
417
   * @param name name of the entity
418
   */
419
  public void startEntity(String name) throws SAXException {
420
      logMetacat.debug("AccessControlList.startEntity ");
421
    if (name.equals("[dtd]")) {
422
        logMetacat.debug("AccessControlList.startEntity  set processingDTD to true.");
423
      processingDTD = true;
424
    }
425
  }
426

    
427
  /** 
428
   * SAX Handler that receives notification of the end of entities.
429
   * @param name name of the entity
430
   */
431
  public void endEntity(String name) throws SAXException {
432
      logMetacat.debug("AccessControlList.endEntity ");
433
    if (name.equals("[dtd]")) {
434
        logMetacat.debug("AccessControlList.endEntity  set processingDTD to false.");
435
      processingDTD = false;
436
    }
437
  }
438

    
439
  /**
440
   * Get the document name.
441
   */
442
  public String getDocname() {
443
    return docname;
444
  }
445

    
446
  /**
447
   * Get the document processing state.
448
   */
449
  public boolean processingDTD() {
450
    return processingDTD;
451
  }
452
  
453
  /* Get all objects associated with @aclid from db.*/
454
  private Vector getACLObjects(String aclid) 
455
          throws SQLException 
456
  {
457
    Vector aclObjects = new Vector();
458
    DBConnection conn = null;
459
    int serialNumber = -1;
460
    PreparedStatement pstmt = null;
461
    try
462
    {
463
      //get connection from DBConnectionPool
464
      conn=DBConnectionPool.getDBConnection("AccessControlList.getACLObject");
465
      serialNumber=conn.getCheckOutSerialNumber();
466
      
467
      // delete all acl records for resources related to @aclid if any
468
      pstmt = conn.prepareStatement(
469
                             "SELECT object FROM xml_relation " +
470
                             "WHERE subject = ? ");
471
      pstmt.setString(1,aclid);
472
      pstmt.execute();
473
      ResultSet rs = pstmt.getResultSet();
474
      boolean hasRows = rs.next();
475
      while (hasRows) {
476
        String object = rs.getString(1);
477
        //System.out.println("add acl object into vector !!!!!!!!!!!!!!!!!"+object);
478
        aclObjects.addElement(object);
479
        hasRows = rs.next();
480
      }//whil
481
    }
482
    catch (SQLException e)
483
    {
484
      throw e;
485
    }
486
    finally
487
    {
488
      try
489
      {
490
        pstmt.close();
491
      }
492
      finally
493
      {
494
        //retrun DBConnection
495
        DBConnectionPool.returnDBConnection(conn,serialNumber);
496
      }
497
    }
498
    
499
    return aclObjects;
500
  }
501

    
502
  /* Delete from db all permission for resources related to @aclid if any.*/
503
  private void deletePermissionsForRelatedResources(String aclid) 
504
          throws SQLException 
505
  {
506
    //DBConnection conn = null;
507
    //int serialNumber = -1;
508
    PreparedStatement pstmt = null;
509
    try
510
    {
511
      //check out DBConenction
512
      //conn=DBConnectionPool.getDBConnection("AccessControlList.deltePerm");
513
      //serialNumber=conn.getCheckOutSerialNumber();
514
    	String sql = "DELETE FROM xml_access WHERE accessfileid = ?";
515
      // delete all acl records for resources related to @aclid if any
516
      pstmt = connection.prepareStatement(sql);
517
      pstmt.setString(1, aclid);
518
      // Increase DBConnection usage count
519
      connection.increaseUsageCount(1);
520
      logMetacat.debug("running sql: " + pstmt.toString());
521
      pstmt.execute();
522
      //increase usageCount!!!!!!
523
      //conn.increaseUsageCount(1);
524
    }
525
    catch (SQLException e)
526
    {
527
      throw e;
528
    }
529
    finally
530
    {
531
      pstmt.close();
532
      //retrun DBConnection
533
      //DBConnectionPool.returnDBConnection(conn,serialNumber);
534
    }
535
  }
536

    
537
  /* Insert into db calculated permission for the list of principals 
538
   * The DBConnection it is use is class field. Because we want to keep rollback
539
   * features and it need use same connection
540
  */
541
  
542
  private void insertPermissions(String docid, String permType ) 
543
                                            throws SQLException 
544
  {
545
    PreparedStatement pstmt = null;
546
    //DBConnection conn = null;
547
    //int serialNumber = -1;
548
    try {
549
      //Check out DBConnection
550
      //conn=DBConnectionPool.getDBConnection("AccessControlList.insertPerm");
551
      //serialNumber=conn.getCheckOutSerialNumber();
552
    	// TODO: look up guid? this is for very old pre-release versions of EML
553
      String guid = docid;
554
      pstmt = connection.prepareStatement(
555
              "INSERT INTO xml_access " + 
556
              "(guid, principal_name, permission, perm_type, perm_order," +
557
              "ticket_count, accessfileid) VALUES " +
558
              "(?,?,?,?,?,?,?)");
559
      // Increase DBConnection usage count
560
      connection.increaseUsageCount(1);
561
      // Bind the values to the query
562
      pstmt.setString(1, guid);
563
      pstmt.setInt(3, permission);
564
      pstmt.setString(4, permType);
565
      pstmt.setString(5, permOrder);
566
      pstmt.setString(7, aclid);
567
      if ( ticketCount > 0 ) {
568
        pstmt.setInt(6, ticketCount);
569
      } else {
570
        pstmt.setInt(6, 0);
571
      }
572
      
573
      //incrase usagecount for DBConnection
574
      //conn.increaseUsageCount(1);
575
      String prName;
576
      for ( int j = 0; j < principal.size(); j++ ) {
577
        prName = (String)principal.elementAt(j);
578
        pstmt.setString(2, prName);
579
        logMetacat.debug("running sql: " + pstmt.toString());
580
        pstmt.execute();
581
      /*    
582
        // check if there are conflict with permission's order
583
        String permOrderOpos = permOrder;
584
        int perm = getPermissions(permission, prName, docid, permOrder);
585
        if (  perm != 0 ) {
586
          if ( permOrder.equals("allowFirst") ) {
587
            permOrderOpos = "denyFirst";
588
          } else if ( permOrder.equals("denyFirst") ) {
589
            permOrderOpos = "allowFirst";
590
          }
591
          throw new SQLException("Permission(s) " + txtValue(perm) + 
592
                    " for \"" + prName + "\" on document #" + docid +
593
                    " has/have been used with \"" + permOrderOpos + "\"");
594
        }
595
      */
596
      }
597
      pstmt.close();
598

    
599
    } catch (SQLException e) {
600
      throw new 
601
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
602
    }
603
    finally
604
    {
605
      pstmt.close();
606
      //return the DBConnection
607
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
608
    }
609
  }
610

    
611
  /* Get permissions with permission order different than @permOrder. */
612
  private int getPermissions(int permission, String principal,
613
                             String docid, String permOrder)
614
          throws SQLException 
615
  {
616
    PreparedStatement pstmt = null;
617
    DBConnection conn = null;
618
    int serialNumber = -1;
619
    try
620
    {
621
      //check out DBConnection
622
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPermissions");
623
      serialNumber=conn.getCheckOutSerialNumber();
624
      pstmt = conn.prepareStatement(
625
            "SELECT permission FROM xml_access " +
626
            "WHERE docid = ? " +
627
            "AND principal_name = ? " +
628
            "AND perm_order NOT = ?");
629
      pstmt.setString(1, docid);
630
      pstmt.setString(2, principal);
631
      pstmt.setString(3, permOrder);
632
      logMetacat.debug("running sql: " + pstmt.toString());
633
      pstmt.execute();
634
      ResultSet rs = pstmt.getResultSet();
635
      boolean hasRow = rs.next();
636
      int perm = 0;
637
      while ( hasRow ) {
638
        perm = rs.getInt(1);
639
        perm = permission & perm;
640
        if ( perm != 0 ) {
641
          pstmt.close();
642
          return perm;
643
        }
644
        hasRow = rs.next();
645
      }
646
    }//try
647
    catch (SQLException e)
648
    {
649
      throw e;
650
    }
651
    finally
652
    {
653
      try
654
      {
655
        pstmt.close();
656
      }
657
      finally
658
      {
659
        DBConnectionPool.returnDBConnection(conn, serialNumber);
660
      }
661
    }
662
    return 0;
663
  }
664

    
665
    /* Get the int value of READ, WRITE, CHMOD or ALL. */
666
	public static int intValue(String permission) {
667
	    
668
		int thisPermission = 0;
669
		try
670
		{
671
		    thisPermission = new Integer(permission).intValue();
672
		    if(thisPermission >= 0 && thisPermission <= 7)
673
		    {
674
		        return thisPermission;
675
		    }
676
		    else
677
		    {
678
		        thisPermission = -1;
679
		    }
680
		}
681
		catch(Exception e)
682
		{ //do nothing.  this must be a word
683
		}
684
		
685
		if (permission.toUpperCase().contains(CHMODSTRING)) {
686
			thisPermission |= CHMOD;
687
		} 
688
		if (permission.toUpperCase().contains(READSTRING)) {
689
			thisPermission |= READ;
690
		} 
691
		if (permission.toUpperCase().contains(WRITESTRING)) {
692
			thisPermission |= WRITE;
693
		} 
694
		if (permission.toUpperCase().contains(ALLSTRING)) {
695
			thisPermission |= ALL;
696
		}
697

    
698
		return thisPermission;
699
	}
700
  
701
  /* Get the text value of READ, WRITE, CHMOD or ALL. */
702
	public static String txtValue(int permission) {
703
		StringBuffer txtPerm = new StringBuffer();
704
		
705
		if ((permission & ALL) == ALL) {
706
			return ALLSTRING;
707
		}		
708
		if ((permission & CHMOD) == CHMOD) {
709
			txtPerm.append(CHMODSTRING);
710
		}
711
		if ((permission & READ) == READ) {
712
			if (txtPerm.length() > 0)
713
				txtPerm.append(",");
714
			txtPerm.append(READSTRING);
715
		}
716
		if ((permission & WRITE) == WRITE) {
717
			if (txtPerm.length() > 0)
718
				txtPerm.append(",");
719
			txtPerm.append(WRITESTRING);
720
		}
721

    
722
		return txtPerm.toString();
723
	}
724

    
725
  /* Get the flag for public "read" access for @docid from db conn. */
726
  private String getPublicAccess(String docid) throws SQLException {
727
    
728
    int publicAcc = 0;
729
    PreparedStatement pstmt = null;
730
    DBConnection conn = null;
731
    int serialNumber = -1;
732
    try
733
    {
734
      //check out DBConnection
735
      conn=DBConnectionPool.getDBConnection("AccessControlList.getPublicAcces");
736
      serialNumber=conn.getCheckOutSerialNumber();
737
      pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
738
                                  "WHERE docid = ?");
739
      pstmt.setString(1, docid);
740
      pstmt.execute();
741
      ResultSet rs = pstmt.getResultSet();
742
      boolean hasRow = rs.next();
743
      if ( hasRow ) {
744
        publicAcc = rs.getInt(1);
745
      }
746
    
747
      return (publicAcc == 1) ? "yes" : "no";
748
    }
749
    finally
750
    {
751
      try
752
      {
753
        pstmt.close();
754
      }
755
      finally
756
      {
757
        DBConnectionPool.returnDBConnection(conn, serialNumber);
758
      }
759
    }
760
  }
761

    
762
  /* Get SystemID for @publicID from Metacat DB Catalog. */
763
  private String getSystemID(String publicID) throws SQLException, PropertyNotFoundException {
764

    
765
		String systemID = "";
766
		PreparedStatement pstmt = null;
767
		DBConnection conn = null;
768
		int serialNumber = -1;
769

    
770
		try {
771
			//check out DBConnection
772
			conn = DBConnectionPool.getDBConnection("AccessControlList.getSystemID");
773
			serialNumber = conn.getCheckOutSerialNumber();
774

    
775
			pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog "
776
					+ "WHERE entry_type = 'DTD' " + "AND public_id = ?");
777
			pstmt.setString(1, publicID);
778
			pstmt.execute();
779
			ResultSet rs = pstmt.getResultSet();
780
			boolean hasRow = rs.next();
781
			if (hasRow) {
782
				systemID = rs.getString(1);
783
				// system id may not have server url on front.  Add it if not.
784
				if (!systemID.startsWith("http://")) {
785
					systemID = SystemUtil.getContextURL() + systemID;
786
				}
787
			}
788

    
789
			return systemID;
790
		}//try
791
		finally {
792
			try {
793
				pstmt.close();
794
			} finally {
795
				DBConnectionPool.returnDBConnection(conn, serialNumber);
796
			}
797
		}//finally
798
	}
799
  
800
  /**
801
   * SAX Handler that receives notification of comments in the DTD
802
   */
803
  public void comment(char[] ch, int start, int length) throws SAXException
804
  {
805
      logMetacat.trace("AccessControlList.comment - starting comment");
806
    
807
  }
808

    
809
  /**
810
   * SAX Handler that receives notification of the start of CDATA sections
811
   */
812
  public void startCDATA() throws SAXException
813
  {
814
      logMetacat.trace("AccessControlList.startCDATA - starting CDATA");
815
  }
816

    
817
  /**
818
   * SAX Handler that receives notification of the end of CDATA sections
819
   */
820
  public void endCDATA() throws SAXException
821
  {
822
      logMetacat.trace("AccessControlList.endCDATA - end CDATA");
823
  }
824
  
825
  public static void main(String[] args) {
826
	  System.out.println("text value for CHMOD (" + CHMOD + "): " + txtValue(CHMOD));
827
	  System.out.println("text value for READ: (" + READ + "): " + txtValue(READ));
828
	  System.out.println("text value for WRITE: (" + WRITE + "): " + txtValue(WRITE));
829
	  System.out.println("text value for ALL: (" + ALL + "): " + txtValue(ALL));
830
	  int chmod_read = CHMOD|READ;
831
	  System.out.println("text value for CHMOD|READ: (" + chmod_read + "): " + txtValue(CHMOD|READ));
832
	  int chmod_write = CHMOD|WRITE;
833
	  System.out.println("text value for CHMOD|WRITE: (" + chmod_write + "): " + txtValue(CHMOD|WRITE));
834
	  int chmod_all = CHMOD|ALL;
835
	  System.out.println("text value for CHMOD|ALL: (" + chmod_all + "): " + txtValue(CHMOD|ALL));
836
	  int read_write = READ|WRITE;
837
	  System.out.println("text value for READ|WRITE: (" + read_write + "): " + txtValue(READ|WRITE));
838
	  int read_all = READ|ALL;
839
	  System.out.println("text value for READ|ALL: (" + read_all + "): " + txtValue(READ|ALL));
840
	  int write_all = WRITE|ALL;
841
	  System.out.println("text value for WRITE|ALL: (" + write_all + "): " + txtValue(WRITE|ALL));
842
	  int chmod_read_write = CHMOD|READ|WRITE;
843
	  System.out.println("text value for CHMOD|READ|WRITE: (" + chmod_read_write + "): " + txtValue(CHMOD|READ|WRITE));
844
	  int chmod_read_all = CHMOD|READ|ALL;
845
	  System.out.println("text value for CHMOD|READ|ALL: (" + chmod_read_all + "): " + txtValue(CHMOD|READ|ALL));
846
	  int chmod_write_all = CHMOD|WRITE|ALL;
847
	  System.out.println("text value for CHMOD|WRITE|ALL: (" + chmod_write_all + "): " + txtValue(CHMOD|WRITE|ALL));
848
	  int read_write_all = READ|WRITE|ALL;
849
	  System.out.println("text value for READ|WRITE|ALL: (" + read_write_all + "): " + txtValue(READ|WRITE|ALL));
850
	  int chmod_read_write_all = CHMOD|READ|WRITE|ALL;
851
	  System.out.println("text value for CHMOD|READ|WRITE|ALL: (" + chmod_read_write_all + "): " + txtValue(CHMOD|READ|WRITE|ALL));
852
	  System.out.println();
853
	  System.out.println("int value for GOOBER: " + intValue("GOOBER"));
854
	  System.out.println("int value for CHANGEPERMISSION: " + intValue("CHANGEPERMISSION"));
855
	  System.out.println("int value for READ: " + intValue("READ"));
856
	  System.out.println("int value for WRITE: " + intValue("WRITE"));
857
	  System.out.println("int value for ALL: " + intValue("ALL"));
858
	  System.out.println("int value for CHANGEPERMISSION,READ: " + intValue("CHANGEPERMISSION,READ"));
859
	  System.out.println("int value for CHANGEPERMISSION,WRITE: " + intValue("CHANGEPERMISSION,WRITE"));
860
	  System.out.println("int value for CHANGEPERMISSION,ALL: " + intValue("CHANGEPERMISSION,ALL"));
861
	  System.out.println("int value for READ,WRITE: " + intValue("READ,WRITE"));
862
	  System.out.println("int value for READ,ALL: " + intValue("READ,ALL"));
863
	  System.out.println("int value for WRITE,ALL: " + intValue("WRITE,ALL"));
864
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE: " + intValue("CHANGEPERMISSION,READ,WRITE"));
865
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,READ,ALL"));
866
	  System.out.println("int value for CHANGEPERMISSION,READ,ALL: " + intValue("CHANGEPERMISSION,WRITE,ALL"));
867
	  System.out.println("int value for READ,WRITE,ALL: " + intValue("READ,WRITE,ALL"));
868
	  System.out.println("int value for CHANGEPERMISSION,READ,WRITE,ALL: " + intValue("CHANGEPERMISSION,READ,WRITE,ALL"));
869
  }
870

    
871
}
(3-3/7)