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
 *    Release: @release@
9
 *
10
 *   '$Author: jones $'
11
 *     '$Date: 2001-09-13 22:28:38 -0700 (Thu, 13 Sep 2001) $'
12
 * '$Revision: 830 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.io.*;
32
import java.sql.*;
33
import java.util.Stack;
34
import java.util.Vector;
35
import java.util.Hashtable;
36
import java.net.URL;
37
import java.net.MalformedURLException;
38

    
39
import org.xml.sax.Attributes;
40
import org.xml.sax.InputSource;
41
import org.xml.sax.ContentHandler;
42
import org.xml.sax.EntityResolver;
43
import org.xml.sax.ErrorHandler;
44
import org.xml.sax.SAXException;
45
import org.xml.sax.SAXParseException;
46
import org.xml.sax.XMLReader;
47
import org.xml.sax.helpers.XMLReaderFactory;
48
import org.xml.sax.helpers.DefaultHandler;
49

    
50
/** 
51
 * A Class that loads eml-access.xml file containing ACL for a metadata
52
 * document into relational DB. It extends DefaultHandler class to handle
53
 * SAX parsing events when processing the XML stream.
54
 */
55
public class AccessControlList extends DefaultHandler {
56

    
57
  private static final int ALL = 1;
58
  private static final int WRITE = 2;
59
  private static final int READ = 4;
60
  private static String sysdate = MetaCatUtil.dbAdapter.getDateTimeFunction();
61
  private static String isnull = MetaCatUtil.dbAdapter.getIsNULLFunction();
62

    
63
  private Connection conn;
64
  private String parserName;
65
  private Stack elementStack;
66
  private String server;
67
  private String sep;
68

    
69
  private boolean	processingDTD;
70
  private String  user;
71
  private String[] groups;
72
  private String  aclid;
73
  private int     rev;
74
  private String 	docname;
75
  private String 	doctype;
76
  private String 	systemid;
77

    
78
  private String docurl;
79
  private Vector resourceURL;
80
  private Vector resourceID;
81
  private Vector principal;
82
  private int    permission;
83
  private String permType;
84
  private String permOrder;
85
//  private String publicAcc;
86
  private String beginTime;
87
  private String endTime;
88
  private int    ticketCount;
89
  private int    serverCode = 1;
90

    
91
  private Vector aclObjects = new Vector();
92
  
93
  /**
94
   * Construct an instance of the AccessControlList class.
95
   * It is used by the permission check up from DBQuery or DocumentImpl
96
   * and from "getaccesscontrol" action
97
   *
98
   * @param conn the JDBC connection where acl info is get
99
   */
100
  public AccessControlList(Connection conn) throws SQLException
101
  {
102
    this.conn = conn;
103
  }
104

    
105
  /**
106
   * Construct an instance of the AccessControlList class.
107
   * It parse acl file and loads acl data into db connection.
108
   *
109
   * @param conn the JDBC connection where acl data are loaded
110
   * @param aclid the Accession# of the document with the acl data
111
   * @param acl the acl file containing acl data
112
   * @param user the user connected to MetaCat servlet and owns the document
113
   * @param groups the groups to which user belongs
114
   * @param serverCode the serverid from xml_replication on which this document
115
   *        resides.
116
   */
117
  public AccessControlList(Connection conn, String aclid, //Reader acl,
118
                           String user, String[] groups, int serverCode)
119
                  throws SAXException, IOException, McdbException
120
  {
121
    String parserName = MetaCatUtil.getOption("saxparser");
122
    this.server = MetaCatUtil.getOption("server");
123
    this.sep = MetaCatUtil.getOption("accNumSeparator");
124

    
125
    this.conn = conn;
126
    this.parserName = parserName;
127
    this.processingDTD = false;
128
    this.elementStack = new Stack();
129
    
130
    this.user = user;
131
    this.groups = groups;
132
    this.aclid = aclid;
133
    this.resourceURL = new Vector();
134
    this.resourceID = new Vector();
135
    this.principal = new Vector();
136
    this.permission = 0;
137
    this.ticketCount = 0;
138
  //  this.publicAcc = null;
139
    this.serverCode = serverCode;
140
    
141
    // read the access file from db connection
142
    DocumentImpl acldoc = new DocumentImpl(conn, aclid);
143
    String acl = acldoc.toString();
144
    this.rev = acldoc.getRev();
145

    
146
    // Initialize the parse
147
    XMLReader parser = initializeParser();
148
    // parse the access file and write the info to xml_access
149
    parser.parse(new InputSource(new StringReader(acl)));
150
    
151
  }
152

    
153
// NOT USED
154
//  /**
155
//   * Construct an instance of the AccessControlList class.
156
//   * It parses eml-access file and loads acl data into db connection.
157
//   * It is used from command line execution.
158
//   *
159
//   * @param conn the JDBC connection where acl data are loaded
160
//   * @param docid the Accession# of the document with the acl data
161
//   * @param aclfilename the name of acl file containing acl data
162
//   * @param user the user connected to MetaCat servlet and owns the document
163
//   * @param groups the groups to which user belongs
164
//   */
165
//  public AccessControlList( Connection conn, String aclid, String aclfilename,
166
//                           String user, String[] groups )
167
//                  throws SAXException, IOException, McdbException
168
//  {
169
//    this(conn, aclid, new FileReader(new File(aclfilename).toString()), 
170
//         user, groups, 1);
171
//  }
172
  
173
  /* Set up the SAX parser for reading the XML serialized ACL */
174
  private XMLReader initializeParser() throws SAXException 
175
  {
176
    XMLReader parser = null;
177

    
178
    // Get an instance of the parser
179
    parser = XMLReaderFactory.createXMLReader(parserName);
180

    
181
    // Turn off validation
182
    parser.setFeature("http://xml.org/sax/features/validation", true);
183
      
184
    // Set Handlers in the parser
185
    // Set the ContentHandler to this instance
186
    parser.setContentHandler((ContentHandler)this);
187

    
188
    // make a DBEntityResolver instance
189
    // Set the EntityReslover to DBEntityResolver instance
190
    EntityResolver eresolver = new DBEntityResolver(conn,this,null);
191
    parser.setEntityResolver((EntityResolver)eresolver);
192

    
193
    // Set the ErrorHandler to this instance
194
    parser.setErrorHandler((ErrorHandler)this);
195

    
196
    return parser;
197
  }
198
  
199
  /**
200
   * Callback method used by the SAX Parser when beginning of the document
201
   */
202
  public void startDocument() throws SAXException 
203
  {
204
    //delete all previously submitted permissions @ relations
205
    //this happens only on UPDATE of the access file
206
    try {
207
      this.aclObjects = getACLObjects(aclid);
208

    
209
      //delete all permissions for resources related to @aclid if any
210
      if ( aclid != null ) {
211
        deletePermissionsForRelatedResources(aclid);
212
      }
213
    } catch (SQLException sqle) {
214
      throw new SAXException(sqle);
215
    }
216
  }
217
  
218
  /**
219
   * Callback method used by the SAX Parser when the start tag of an 
220
   * element is detected. Used in this context to parse and store
221
   * the acl information in class variables.
222
   */
223
  public void startElement (String uri, String localName, 
224
                            String qName, Attributes atts) 
225
         throws SAXException 
226
  {
227
    BasicNode currentNode = new BasicNode(localName);
228
    if (atts != null) {
229
      int len = atts.getLength();
230
      for (int i = 0; i < len; i++) {
231
        currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i));
232
      }
233
    }
234
    if ( currentNode.getTagName().equals("acl") ) {
235
      permOrder = currentNode.getAttribute("order");
236
    //  publicAcc = currentNode.getAttribute("public");
237
    }
238
    elementStack.push(currentNode); 
239
  }
240

    
241
  /**
242
   * Callback method used by the SAX Parser when the text sequences of an 
243
   * xml stream are detected. Used in this context to parse and store
244
   * the acl information in class variables.
245
   */
246
  public void characters(char ch[], int start, int length)
247
         throws SAXException 
248
  {
249
    String inputString = new String(ch, start, length);
250
    BasicNode currentNode = (BasicNode)elementStack.peek(); 
251
    String currentTag = currentNode.getTagName();
252

    
253
      if (currentTag.equals("principal")) {
254

    
255
        principal.addElement(inputString);
256

    
257
      } else if (currentTag.equals("permission")) {
258

    
259
        if ( inputString.trim().toUpperCase().equals("READ") ) {
260
          permission = permission | READ;
261
        } else if ( inputString.trim().toUpperCase().equals("WRITE") ) {
262
          permission = permission | WRITE;
263
        } else if ( inputString.trim().toUpperCase().equals("ALL") ) {
264
          permission = permission | ALL;
265
        } else {
266
          throw new SAXException("Unknown permission type: " + inputString);
267
        }
268

    
269
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
270
        beginTime = inputString.trim();
271

    
272
      } else if ( currentTag.equals("stopDate") && endTime == null) {
273
        endTime = inputString.trim();
274

    
275
      } else if (currentTag.equals("ticketCount") && ticketCount == 0 ) {
276
        try {
277
          ticketCount = (new Integer(inputString.trim())).intValue();
278
        } catch (NumberFormatException nfe) {
279
          throw new SAXException("Wrong integer format for:" + inputString);
280
        }
281
      }
282
  }
283

    
284
  /**
285
   * Callback method used by the SAX Parser when the end tag of an 
286
   * element is detected. Used in this context to parse and store
287
   * the acl information in class variables.
288
   */
289
  public void endElement (String uri, String localName, String qName)
290
         throws SAXException 
291
  {
292
    BasicNode leaving = (BasicNode)elementStack.pop();
293
    String leavingTagName = leaving.getTagName();
294

    
295
    if ( leavingTagName.equals("allow") ||
296
         leavingTagName.equals("deny")    ) {
297
      
298
      if ( permission > 0 ) {
299

    
300
        // insert into db calculated permission for the list of principals
301
        try {
302
// System.out.println("before insertPermission " +leavingTagName);
303
          // go through the objects in xml_relation about this acl doc
304
          for (int i=0; i < aclObjects.size(); i++) {
305
            // docid of the current object
306
            String docid = (String)aclObjects.elementAt(i); 
307
            DocumentIdentifier docID = new DocumentIdentifier(docid);
308
            docid = docID.getIdentifier();
309
// System.out.println(docid);
310
            insertPermissions(docid,leavingTagName);
311
          }
312

    
313
        } catch (SQLException sqle) {
314
          throw new SAXException(sqle);
315
        } catch (Exception e) {
316
          throw new SAXException(e);
317
        }
318
      }
319

    
320
      // reset the allow/deny permission
321
      principal = new Vector();
322
      permission = 0;
323
      beginTime = null;
324
      endTime = null;
325
      ticketCount = 0;
326
    
327
    }
328

    
329
  }
330

    
331
  /** 
332
    * SAX Handler that receives notification of DOCTYPE. Sets the DTD.
333
    * @param name name of the DTD
334
    * @param publicId Public Identifier of the DTD
335
    * @param systemId System Identifier of the DTD
336
    */
337
  public void startDTD(String name, String publicId, String systemId) 
338
              throws SAXException {
339
    docname = name;
340
    doctype = publicId;
341
    systemid = systemId;
342
  }
343

    
344
  /** 
345
   * SAX Handler that receives notification of the start of entities.
346
   * @param name name of the entity
347
   */
348
  public void startEntity(String name) throws SAXException {
349
    if (name.equals("[dtd]")) {
350
      processingDTD = true;
351
    }
352
  }
353

    
354
  /** 
355
   * SAX Handler that receives notification of the end of entities.
356
   * @param name name of the entity
357
   */
358
  public void endEntity(String name) throws SAXException {
359
    if (name.equals("[dtd]")) {
360
      processingDTD = false;
361
    }
362
  }
363

    
364
  /**
365
   * Get the document name.
366
   */
367
  public String getDocname() {
368
    return docname;
369
  }
370

    
371
  /**
372
   * Get the document processing state.
373
   */
374
  public boolean processingDTD() {
375
    return processingDTD;
376
  }
377
  
378
  /* Get all objects associated with @aclid from db.*/
379
  private Vector getACLObjects(String aclid) 
380
          throws SQLException 
381
  {
382
    Vector aclObjects = new Vector();
383
    // delete all acl records for resources related to @aclid if any
384
    PreparedStatement pstmt = conn.prepareStatement(
385
                             "SELECT object FROM xml_relation " +
386
                             "WHERE subject = ? ");
387
    pstmt.setString(1,aclid);
388
    pstmt.execute();
389
    ResultSet rs = pstmt.getResultSet();
390
    boolean hasRows = rs.next();
391
    while (hasRows) {
392
      aclObjects.addElement(rs.getString(1));
393
      hasRows = rs.next();
394
    }
395
    
396
    pstmt.close();
397
    
398
    return aclObjects;
399
  }
400

    
401
  /* Delete from db all permission for resources related to @aclid if any.*/
402
  private void deletePermissionsForRelatedResources(String aclid) 
403
          throws SQLException 
404
  {
405
    // delete all acl records for resources related to @aclid if any
406
    Statement stmt = conn.createStatement();
407
    stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + aclid + "'");
408
    stmt.close();
409
  }
410

    
411
  /* Insert into db calculated permission for the list of principals */
412
  private void insertPermissions(String docid, String permType ) 
413
          throws SQLException 
414
  {
415
    PreparedStatement pstmt;
416
 
417
    try {
418
      pstmt = conn.prepareStatement(
419
              "INSERT INTO xml_access " + 
420
              "(docid, principal_name, permission, perm_type, perm_order," +
421
              "begin_time,end_time,ticket_count, accessfileid) VALUES " +
422
              "(?,?,?,?,?,to_date(?,'mm/dd/yy'),to_date(?,'mm/dd/yy'),?,?)");
423
      // Bind the values to the query
424
      pstmt.setString(1, docid);
425
      pstmt.setInt(3, permission);
426
      pstmt.setString(4, permType);
427
      pstmt.setString(5, permOrder);
428
      pstmt.setString(6, beginTime);
429
      pstmt.setString(7, endTime);
430
      pstmt.setString(9, aclid);
431
      if ( ticketCount > 0 ) {
432
        pstmt.setString(8, "" + ticketCount);
433
      } else {
434
        pstmt.setString(8, "");
435
      }
436

    
437
      String prName;
438
      for ( int j = 0; j < principal.size(); j++ ) {
439
        prName = (String)principal.elementAt(j);
440
        pstmt.setString(2, prName);
441
        pstmt.execute();
442
      /*    
443
        // check if there are conflict with permission's order
444
        String permOrderOpos = permOrder;
445
        int perm = getPermissions(permission, prName, docid, permOrder);
446
        if (  perm != 0 ) {
447
          if ( permOrder.equals("allowFirst") ) {
448
            permOrderOpos = "denyFirst";
449
          } else if ( permOrder.equals("denyFirst") ) {
450
            permOrderOpos = "allowFirst";
451
          }
452
          throw new SQLException("Permission(s) " + txtValue(perm) + 
453
                    " for \"" + prName + "\" on document #" + docid +
454
                    " has/have been used with \"" + permOrderOpos + "\"");
455
        }
456
      */
457
      }
458
      pstmt.close();
459

    
460
    } catch (SQLException e) {
461
      throw new 
462
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
463
    }
464
  }
465

    
466
  /* Get permissions with permission order different than @permOrder. */
467
  private int getPermissions(int permission, String principal,
468
                             String docid, String permOrder)
469
          throws SQLException 
470
  {
471
    PreparedStatement pstmt;
472
    pstmt = conn.prepareStatement(
473
            "SELECT permission FROM xml_access " +
474
            "WHERE docid = ? " +
475
            "AND principal_name = ? " +
476
            "AND perm_order NOT = ?");
477
    pstmt.setString(1, docid);
478
    pstmt.setString(2, principal);
479
    pstmt.setString(3, permOrder);
480
    pstmt.execute();
481
    ResultSet rs = pstmt.getResultSet();
482
    boolean hasRow = rs.next();
483
    int perm = 0;
484
    while ( hasRow ) {
485
      perm = rs.getInt(1);
486
      perm = permission & perm;
487
      if ( perm != 0 ) {
488
        pstmt.close();
489
        return perm;
490
      }
491
      hasRow = rs.next();
492
    }
493
    pstmt.close();
494
    return 0;
495
  }
496

    
497
  /* Get the int value of READ, WRITE or ALL. */
498
  private int intValue ( String permission )
499
  {
500
    if ( permission.equals("READ") ) {
501
      return READ;
502
    } else if ( permission.equals("WRITE") ) {
503
      return WRITE;
504
    } else if ( permission.equals("ALL") ) {
505
      return ALL;
506
    }
507
    
508
    return -1;
509
  }
510

    
511
  /* Get the text value of READ, WRITE or ALL. */
512
  private String txtValue ( int permission )
513
  {
514
    StringBuffer txtPerm = new StringBuffer("\"");
515
    if ( (permission & READ) != 0 ) {
516
      txtPerm.append("read");
517
    } 
518
    if ( (permission & WRITE) != 0 ) {
519
      if ( txtPerm.length() > 0 ) txtPerm.append(",");
520
      txtPerm.append("write");
521
    }
522
    if ( (permission & ALL) != 0 ) {
523
      if ( txtPerm.length() > 0 ) txtPerm.append(",");
524
      txtPerm.append("all");
525
    }
526

    
527
    return txtPerm.append("\"").toString();
528
  }
529

    
530
  /**
531
    * Check from db connection if at least one of the list of @principals
532
    * has @permission on @docid.
533
    * @param permission permission type to check for
534
    * @param principals list of names of principals to check for @permission
535
    * @param docid document identifier to check on
536
    */
537
  public boolean hasPermission(String permission, String user,
538
                               String[] groups, String docid )
539
                 throws SQLException
540
  {
541
    // b' of the command line invocation
542
    if ( (user == null) && (groups == null || groups.length == 0) ) {
543
      return true;
544
    }
545
    
546
    // Check for @permission on @docid for @user and/or @groups
547
    boolean hasPermission = hasPermission(permission,user,docid);
548
    int i = 0;
549
    if ( groups != null ) {
550
      while ( !hasPermission && i<groups.length ) {
551
        hasPermission = hasPermission(permission,groups[i++],docid);
552
      }
553
    }
554
    // Check for @permission for "public" user
555
    if ( !hasPermission ) {
556
      hasPermission = hasPermission(permission,"public",docid);
557
    }
558
    
559
    return hasPermission;
560
  }
561

    
562
  /**
563
    * Check from db connection if @principal has @permission on @docid.
564
    * @param permission permission type to check for
565
    * @param principal name of principal to check for @permission
566
    * @param docid document identifier to check on
567
    */
568
  private boolean hasPermission(String permission,
569
                                String principal, String docid)
570
                 throws SQLException
571
  {
572
    PreparedStatement pstmt;
573
    // check public access to @docid from xml_documents table
574
    if ( permission.equals("READ") ) {
575
      try {
576
        pstmt = conn.prepareStatement(
577
                "SELECT 'x' FROM xml_documents " +
578
                "WHERE docid = ? AND public_access = 1");
579
        // Bind the values to the query
580
        pstmt.setString(1, docid);
581

    
582
        pstmt.execute();
583
        ResultSet rs = pstmt.getResultSet();
584
        boolean hasRow = rs.next();
585
        pstmt.close();
586
        if (hasRow) {
587
          return true;
588
        }
589
//System.out.println("Passed the check for public access");      
590

    
591
      } catch (SQLException e) {
592
        throw new 
593
        SQLException("AccessControlList.hasPermission(). " +
594
                     "Error checking public access for document #"+docid+
595
                     ". " + e.getMessage());
596
      }
597
    }
598
    
599
    // since owner of resource has all permission on it,
600
    // check if @principal is owner of @docid in xml_documents table
601
    if ( principal != null ) {
602
      try {
603
        pstmt = conn.prepareStatement(
604
                "SELECT 'x' FROM xml_documents " +
605
                "WHERE docid = ? AND user_owner = ?");
606
        // Bind the values to the query
607
        pstmt.setString(1, docid);
608
        pstmt.setString(2, principal);
609

    
610
        pstmt.execute();
611
        ResultSet rs = pstmt.getResultSet();
612
        boolean hasRow = rs.next();
613
        pstmt.close();
614
        if (hasRow) {
615
          return true;
616
        }
617
//System.out.println("Passed the check for ownership");      
618
     
619
      } catch (SQLException e) {
620
        throw new 
621
        SQLException("AccessControlList.hasPermission(). " +
622
                     "Error checking ownership for " + principal +
623
                     " on document #" + docid + ". " + e.getMessage());
624
      }
625

    
626
      // check @principal's @permission on @docid from xml_access table
627
      int accessValue = 0;
628
      int ticketCount = 0;
629
      String permOrder = "";
630
      try {
631
        pstmt = conn.prepareStatement(
632
                "SELECT permission, perm_order, ticket_count " +
633
                "FROM xml_access " +
634
                "WHERE docid = ? " + 
635
                "AND principal_name = ? " +
636
                "AND perm_type = ? " +
637
                "AND " + sysdate + 
638
                " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
639
                     "AND " + isnull + "(end_time," + sysdate + ")");
640
        // check if it is "deny" with "allowFirst" first
641
        // Bind the values to the query
642
        pstmt.setString(1, docid);
643
        pstmt.setString(2, principal);
644
        pstmt.setString(3, "deny");
645

    
646
        pstmt.execute();
647
        ResultSet rs = pstmt.getResultSet();
648
        boolean hasRows = rs.next();
649
        while ( hasRows ) {
650
          accessValue = rs.getInt(1);
651
          permOrder = rs.getString(2);
652
          ticketCount = rs.getInt(3);
653
          if ( ( accessValue & intValue(permission) ) == intValue(permission) &&
654
               ( permOrder.equals("allowFirst") ) &&
655
               ( rs.wasNull() || ticketCount > 0 ) ) {
656
            if ( !rs.wasNull() && ticketCount > 0 ) {
657
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","allowFirst");
658
            }
659
            pstmt.close();
660
            return false;
661
          }
662
          hasRows = rs.next();
663
        }
664
//System.out.println("Passed the check for \"deny\" access with \"allowFirst\"");      
665

    
666
        // it is not denied then check if it is "allow"
667
        // Bind the values to the query
668
        pstmt.setString(1, docid);
669
        pstmt.setString(2, principal);
670
        pstmt.setString(3, "allow");
671

    
672
        pstmt.execute();
673
        rs = pstmt.getResultSet();
674
        hasRows = rs.next();
675
        while ( hasRows ) {
676
          accessValue = rs.getInt(1);
677
          permOrder = rs.getString(2);
678
          ticketCount = rs.getInt(3);
679
          if ( ( accessValue & intValue(permission) )==intValue(permission) &&
680
               ( rs.wasNull() || ticketCount > 0 ) ) {
681
            if ( !rs.wasNull() && ticketCount > 0 ) {
682
              decreaseNumberOfAccess(accessValue,principal,docid,"allow",permOrder);
683
            }
684
            pstmt.close();
685
            return true;
686
          }
687
          hasRows = rs.next();
688
        }
689
//System.out.println("Passed the check for \"allow\" access");      
690

    
691
        // it is not allowed then check if it is "deny" with "denyFirst"
692
        // Bind the values to the query
693
        pstmt.setString(1, docid);
694
        pstmt.setString(2, principal);
695
        pstmt.setString(3, "deny");
696

    
697
        pstmt.execute();
698
        rs = pstmt.getResultSet();
699
        hasRows = rs.next();
700
        while ( hasRows ) {
701
          accessValue = rs.getInt(1);
702
          permOrder = rs.getString(2);
703
          ticketCount = rs.getInt(3);
704
          if ( ( accessValue & intValue(permission) ) == intValue(permission) &&
705
               ( permOrder.equals("denyFirst") ) &&
706
               ( rs.wasNull() || ticketCount > 0 ) ) {
707
            if ( !rs.wasNull() && ticketCount > 0 ) {
708
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","denyFirst");
709
            }
710
            pstmt.close();
711
            return false;
712
          }
713
          hasRows = rs.next();
714
        }
715
//System.out.println("Passed the check for \"deny\" access wirh \"denyFirst\"");      
716
      
717
        pstmt.close();
718
        return false;
719
  
720
      } catch (SQLException e) {
721
        throw new 
722
        SQLException("AccessControlList.hasPermission(). " +
723
                     "Error checking " + permission + " permission for " +
724
                     principal + " on document #" + docid + ". " +
725
                     e.getMessage());
726
      }
727
    }
728
    
729
    return false;
730
  }
731

    
732
  /* Decrease the number of access to @docid for @principal in db. */
733
  private void decreaseNumberOfAccess(int permission, String principal,
734
                                      String docid, String permType, 
735
                                      String permOrder) 
736
               throws SQLException
737
  {
738
    PreparedStatement pstmt;
739
    pstmt = conn.prepareStatement(
740
            "UPDATE xml_access SET ticket_count = ticket_count - 1 " +
741
            "WHERE docid = ? " +
742
            "AND principal_name = ? " +
743
            "AND permission = ? " +
744
            "AND perm_type = ? " +
745
            "AND perm_order = ? " +
746
            "AND " + sysdate + 
747
            " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
748
                 "AND " + isnull + "(end_time," + sysdate + ")");
749
    // Bind the values to the query
750
    pstmt.setString(1, docid);
751
    pstmt.setString(2, principal);
752
    pstmt.setInt(3, permission);
753
    pstmt.setString(4, permType);
754
    pstmt.setString(5, permOrder);
755

    
756
    pstmt.execute();
757
    pstmt.close();
758
  }
759
 
760
 
761
  /**
762
    * Get Access Control List information for document from db connetion.
763
    * User or Group should have permissions for reading
764
    * access control information for a document specified by @docid.
765
    * @param docid document identifier which acl info to get
766
    * @param user name of user connected to Metacat system
767
    * @param groups names of user's groups to which user belongs
768
    */
769
  public String getACL(String docid, String user, String[] groups) 
770
          throws SQLException 
771
  {
772
    StringBuffer output = new StringBuffer();
773
    StringBuffer outTemp = new StringBuffer();
774
    MetaCatUtil util = new MetaCatUtil();
775
    String accDoctype = util.getOption("accessdoctype");
776
    String server = util.getOption("server");
777
    String docurl = "metacat://" + server + "/?docid=" + docid;
778
    String systemID;
779
    boolean isOwned = false;
780
    boolean hasPermission = false;
781
    String publicAcc;
782
    
783
    String acfid = "";
784
    String acfid_prev = "";
785
    String principal;
786
    Vector principalArr = new Vector();
787
    int permission;
788
    int perm_prev = -1;
789
    String permType;
790
    String permOrder = "";
791
    String permOrder_prev = "";
792
    String beginTime = "";
793
    String begin_prev = "";
794
    String endTime = "";
795
    String end_prev = "";
796
    int ticketCount = -1;
797
    int ticket_prev = -1;
798
    
799
    try {
800
      
801
      isOwned = isOwned(docid, user);
802
      systemID = getSystemID(accDoctype);
803
      publicAcc = getPublicAccess(docid);
804
        
805
      output.append("<?xml version=\"1.0\"?>\n");
806
      output.append("<!DOCTYPE acl PUBLIC \"" + accDoctype + "\" \"" +
807
                    systemID + "\">\n");
808
      output.append("<acl authSystem=\"\">\n");
809

    
810
      PreparedStatement pstmt;
811
      pstmt = conn.prepareStatement(
812
              "SELECT distinct accessfileid, principal_name, permission, " +
813
              "perm_type, perm_order, to_char(begin_time,'mm/dd/yyyy'), " +
814
              "to_char(end_time,'mm/dd/yyyy'), ticket_count " +
815
              "FROM xml_access WHERE docid = ? " +
816
              "ORDER BY accessfileid, perm_order, perm_type, permission");
817
      // Bind the values to the query
818
      pstmt.setString(1, docid);
819
      pstmt.execute();
820
      ResultSet rs = pstmt.getResultSet();
821
      boolean hasRows = rs.next();
822
      while (hasRows) {
823

    
824
        acfid = rs.getString(1);
825
        principal = rs.getString(2);
826
        permission = rs.getInt(3);
827
        permType = rs.getString(4);
828
        permOrder = rs.getString(5);
829
        beginTime = rs.getString(6);
830
        endTime = rs.getString(7);
831
        ticketCount = rs.getInt(8);
832

    
833
        // if @docid is not owned by @user, only ACL info from that
834
        // access files to which @user/@groups has "read" permission
835
        // is extracted
836
        if ( !isOwned ) {
837
          if ( !acfid.equals(acfid_prev) ) {
838
            acfid_prev = acfid;
839
            hasPermission = this.hasPermission("READ",user,groups,acfid);
840
          }
841
          if ( !hasPermission ) {
842
            rs.next();
843
            continue;
844
          }
845
        }
846
        
847
        // open <resource> tag
848
        if ( !permOrder.equals(permOrder_prev) ) {
849
          // close </resource> tag if any was opened 
850
          output.append(outTemp.toString());
851
          outTemp = new StringBuffer();
852
          if ( !permOrder_prev.equals("") ) {
853
            output.append("  </resource>\n");
854
          }
855
          output.append("  <resource order=\"" + permOrder + "\" public=\"" +
856
                        publicAcc + "\">\n");
857
          output.append("    <resourceIdentifier>" + docurl + 
858
                        "</resourceIdentifier>\n");
859
          permOrder_prev = permOrder;
860
        }
861
        
862
        // close </allow> or </deny> tag then open new one
863
        if ( permission != perm_prev ||
864
             (endTime == null) && (end_prev != null) ||
865
             (beginTime == null) && (begin_prev != null) ||
866
             endTime != null && !endTime.equals(end_prev)  ||
867
             beginTime != null && !beginTime.equals(begin_prev) ||
868
             ticketCount != ticket_prev )  {
869
          output.append(outTemp.toString());
870
          outTemp = new StringBuffer();
871
          principalArr.removeAllElements();
872
          output.append("    <" + permType + ">\n");
873
        }
874
        
875
        // put all principals here for the same 
876
        // permission, duration and ticket_count
877
        if ( !principalArr.contains(principal) ) {
878
          principalArr.addElement(principal);
879
          output.append("      <principal>" + principal + "</principal>\n");
880
        } 
881
        
882
        // prepare <permission> tags, <duration> and <ticketCount>
883
        // if any to put within <allow> (<deny>) by next cicle
884
        if ( permission != perm_prev || 
885
             (endTime == null) && (end_prev != null) ||
886
             (beginTime == null) && (begin_prev != null) ||
887
             endTime != null && !endTime.equals(end_prev)  ||
888
             beginTime != null && !beginTime.equals(begin_prev) ||
889
             ticketCount != ticket_prev )  {
890
          if ( (permission & READ) != 0 ) {
891
            outTemp.append("      <permission>read</permission>\n");
892
          }
893
          if ( (permission & WRITE) != 0 ) {
894
            outTemp.append("      <permission>write</permission>\n");
895
          }
896
          if ( (permission & ALL) != 0 ) {
897
            outTemp.append("      <permission>all</permission>\n");
898
          }
899
          if ( (beginTime != null) || (endTime != null) ) {
900
            outTemp.append("      <duration>" + beginTime + " " + endTime +
901
                          "</duration>\n");
902
          }
903
          if ( ticketCount > 0 ) {
904
            outTemp.append("      <ticketCount>" + ticketCount + 
905
                          "</ticketCount>\n");
906
          }
907
          outTemp.append("    </" + permType + ">\n");
908
          perm_prev = permission;
909
          ticket_prev = ticketCount;
910
          begin_prev = beginTime;
911
          end_prev = endTime;
912
        }
913
        
914
        hasRows = rs.next();
915
      }
916

    
917
      // close <allow> or <deny> if anything left in outTemp var
918
      output.append(outTemp.toString());
919

    
920
      // If there are no any acl info for @docid accessible by @user/@group,
921
      // extract only the following information
922
      if ( permOrder.equals("") ) {
923
        output.append("  <resource public=\"" + publicAcc + "\">\n");
924
        output.append("    <resourceIdentifier>" + docurl + 
925
                      "</resourceIdentifier>\n");
926
      }
927
      
928
      // always close them
929
      output.append("  </resource>\n");
930
      output.append("</acl>\n");
931
      
932
      pstmt.close();
933

    
934
      return output.toString();
935

    
936
    } catch (SQLException e) {
937
      throw new 
938
      SQLException("AccessControlList.getACL(). " + e.getMessage());
939
    }
940
  }
941
  
942
  /* Check if @user is owner of @docid from db conn. */
943
  private boolean isOwned(String docid, String user) throws SQLException {
944
    
945
    PreparedStatement pstmt;
946
    pstmt = conn.prepareStatement("SELECT 'x' FROM xml_documents " +
947
                                  "WHERE docid = ? " + 
948
                                  "AND user_owner = ?");
949
    pstmt.setString(1, docid);
950
    pstmt.setString(2, user);
951
    pstmt.execute();
952
    ResultSet rs = pstmt.getResultSet();
953
    boolean hasRow = rs.next();
954
    
955
    return hasRow;
956
  }
957

    
958
  /* Get the flag for public "read" access for @docid from db conn. */
959
  private String getPublicAccess(String docid) throws SQLException {
960
    
961
    int publicAcc = 0;
962
    PreparedStatement pstmt;
963
    pstmt = conn.prepareStatement("SELECT public_access FROM xml_documents " +
964
                                  "WHERE docid = ?");
965
    pstmt.setString(1, docid);
966
    pstmt.execute();
967
    ResultSet rs = pstmt.getResultSet();
968
    boolean hasRow = rs.next();
969
    if ( hasRow ) {
970
      publicAcc = rs.getInt(1);
971
    }
972
    
973
    return (publicAcc == 1) ? "yes" : "no";
974
  }
975

    
976
  /* Get SystemID for @publicID from Metacat DB Catalog. */
977
  private String getSystemID(String publicID) throws SQLException {
978
    
979
    String systemID = "";
980
    PreparedStatement pstmt;
981
    pstmt = conn.prepareStatement("SELECT system_id FROM xml_catalog " +
982
                                  "WHERE entry_type = 'DTD' " + 
983
                                  "AND public_id = ?");
984
    pstmt.setString(1, publicID);
985
    pstmt.execute();
986
    ResultSet rs = pstmt.getResultSet();
987
    boolean hasRow = rs.next();
988
    if ( hasRow ) {
989
      systemID = rs.getString(1);
990
    }
991
    
992
    return systemID;
993
  }
994

    
995
}
(1-1/40)