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
 *    Release: @release@
9
 *
10
 *   '$Author$'
11
 *     '$Date$'
12
 * '$Revision$'
13 669 jones
 *
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 555 bojilova
 */
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 652 bojilova
import java.util.Hashtable;
36
import java.net.URL;
37
import java.net.MalformedURLException;
38 555 bojilova
39
import org.xml.sax.Attributes;
40
import org.xml.sax.InputSource;
41 598 bojilova
import org.xml.sax.ContentHandler;
42
import org.xml.sax.EntityResolver;
43
import org.xml.sax.ErrorHandler;
44 555 bojilova
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 774 bojilova
  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 555 bojilova
63 570 bojilova
  private Connection conn;
64 555 bojilova
  private String parserName;
65
  private Stack elementStack;
66 645 bojilova
  private String server;
67 802 bojilova
  private String sep;
68 555 bojilova
69 598 bojilova
  private boolean	processingDTD;
70 645 bojilova
  private String  user;
71 802 bojilova
  private String[] groups;
72 638 bojilova
  private String  aclid;
73 802 bojilova
  private int     rev;
74 598 bojilova
  private String 	docname;
75
  private String 	doctype;
76
  private String 	systemid;
77
78 665 bojilova
  private String docurl;
79
  private Vector resourceURL;
80
  private Vector resourceID;
81 660 bojilova
  private Vector principal;
82 570 bojilova
  private int    permission;
83
  private String permType;
84
  private String permOrder;
85 802 bojilova
//  private String publicAcc;
86 570 bojilova
  private String beginTime;
87
  private String endTime;
88
  private int    ticketCount;
89 684 bojilova
  private int    serverCode = 1;
90 802 bojilova
91
  private Vector aclObjects = new Vector();
92 638 bojilova
93 555 bojilova
  /**
94
   * Construct an instance of the AccessControlList class.
95 688 bojilova
   * It is used by the permission check up from DBQuery or DocumentImpl
96
   * and from "getaccesscontrol" action
97 570 bojilova
   *
98 684 bojilova
   * @param conn the JDBC connection where acl info is get
99 570 bojilova
   */
100 684 bojilova
  public AccessControlList(Connection conn) throws SQLException
101 570 bojilova
  {
102 613 bojilova
    this.conn = conn;
103 570 bojilova
  }
104
105
  /**
106
   * Construct an instance of the AccessControlList class.
107 555 bojilova
   * It parse acl file and loads acl data into db connection.
108
   *
109
   * @param conn the JDBC connection where acl data are loaded
110 684 bojilova
   * @param aclid the Accession# of the document with the acl data
111 570 bojilova
   * @param acl the acl file containing acl data
112 684 bojilova
   * @param user the user connected to MetaCat servlet and owns the document
113 802 bojilova
   * @param groups the groups to which user belongs
114 684 bojilova
   * @param serverCode the serverid from xml_replication on which this document
115
   *        resides.
116 555 bojilova
   */
117 819 bojilova
  public AccessControlList(Connection conn, String aclid, //Reader acl,
118 802 bojilova
                           String user, String[] groups, int serverCode)
119 819 bojilova
                  throws SAXException, IOException, McdbException
120 555 bojilova
  {
121 802 bojilova
    String parserName = MetaCatUtil.getOption("saxparser");
122
    this.server = MetaCatUtil.getOption("server");
123
    this.sep = MetaCatUtil.getOption("accNumSeparator");
124 555 bojilova
125
    this.conn = conn;
126
    this.parserName = parserName;
127 598 bojilova
    this.processingDTD = false;
128 570 bojilova
    this.elementStack = new Stack();
129
130 645 bojilova
    this.user = user;
131 802 bojilova
    this.groups = groups;
132 638 bojilova
    this.aclid = aclid;
133 665 bojilova
    this.resourceURL = new Vector();
134
    this.resourceID = new Vector();
135 660 bojilova
    this.principal = new Vector();
136 570 bojilova
    this.permission = 0;
137
    this.ticketCount = 0;
138 802 bojilova
  //  this.publicAcc = null;
139 684 bojilova
    this.serverCode = serverCode;
140 638 bojilova
141 819 bojilova
    // 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 555 bojilova
    XMLReader parser = initializeParser();
148 819 bojilova
    // parse the access file and write the info to xml_access
149
    parser.parse(new InputSource(new StringReader(acl)));
150
151 555 bojilova
  }
152
153 819 bojilova
// 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 638 bojilova
173 660 bojilova
  /* Set up the SAX parser for reading the XML serialized ACL */
174 555 bojilova
  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 598 bojilova
    // Turn off validation
182 638 bojilova
    parser.setFeature("http://xml.org/sax/features/validation", true);
183 598 bojilova
184
    // Set Handlers in the parser
185 555 bojilova
    // Set the ContentHandler to this instance
186 598 bojilova
    parser.setContentHandler((ContentHandler)this);
187 555 bojilova
188 598 bojilova
    // 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 555 bojilova
    // Set the ErrorHandler to this instance
194 598 bojilova
    parser.setErrorHandler((ErrorHandler)this);
195 555 bojilova
196
    return parser;
197
  }
198
199
  /**
200 688 bojilova
   * Callback method used by the SAX Parser when beginning of the document
201 645 bojilova
   */
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 819 bojilova
      this.aclObjects = getACLObjects(aclid);
208 802 bojilova
209 819 bojilova
      //delete all permissions for resources related to @aclid if any
210 645 bojilova
      if ( aclid != null ) {
211
        deletePermissionsForRelatedResources(aclid);
212
      }
213
    } catch (SQLException sqle) {
214
      throw new SAXException(sqle);
215
    }
216
  }
217
218
  /**
219 688 bojilova
   * Callback method used by the SAX Parser when the start tag of an
220 555 bojilova
   * 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 802 bojilova
    if ( currentNode.getTagName().equals("acl") ) {
235 570 bojilova
      permOrder = currentNode.getAttribute("order");
236 802 bojilova
    //  publicAcc = currentNode.getAttribute("public");
237 570 bojilova
    }
238 555 bojilova
    elementStack.push(currentNode);
239
  }
240
241
  /**
242 688 bojilova
   * Callback method used by the SAX Parser when the text sequences of an
243 555 bojilova
   * 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 802 bojilova
      if (currentTag.equals("principal")) {
254 645 bojilova
255 802 bojilova
        principal.addElement(inputString);
256 645 bojilova
257 802 bojilova
      } else if (currentTag.equals("permission")) {
258 645 bojilova
259 802 bojilova
        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 645 bojilova
269 802 bojilova
      } else if ( currentTag.equals("startDate") && beginTime == null ) {
270
        beginTime = inputString.trim();
271 645 bojilova
272 802 bojilova
      } else if ( currentTag.equals("stopDate") && endTime == null) {
273
        endTime = inputString.trim();
274 645 bojilova
275 802 bojilova
      } 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 555 bojilova
      }
282
  }
283
284
  /**
285 688 bojilova
   * Callback method used by the SAX Parser when the end tag of an
286 555 bojilova
   * 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 688 bojilova
    BasicNode leaving = (BasicNode)elementStack.pop();
293
    String leavingTagName = leaving.getTagName();
294
295 802 bojilova
    if ( leavingTagName.equals("allow") ||
296
         leavingTagName.equals("deny")    ) {
297 570 bojilova
298
      if ( permission > 0 ) {
299 555 bojilova
300 570 bojilova
        // insert into db calculated permission for the list of principals
301
        try {
302 802 bojilova
// 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 570 bojilova
        } catch (SQLException sqle) {
314
          throw new SAXException(sqle);
315 802 bojilova
        } catch (Exception e) {
316
          throw new SAXException(e);
317 570 bojilova
        }
318
      }
319
320 688 bojilova
      // reset the allow/deny permission
321 660 bojilova
      principal = new Vector();
322 555 bojilova
      permission = 0;
323 570 bojilova
      beginTime = null;
324
      endTime = null;
325
      ticketCount = 0;
326 555 bojilova
327 570 bojilova
    }
328 555 bojilova
329
  }
330 598 bojilova
331 688 bojilova
  /**
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 598 bojilova
  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 688 bojilova
   * SAX Handler that receives notification of the start of entities.
346
   * @param name name of the entity
347 598 bojilova
   */
348
  public void startEntity(String name) throws SAXException {
349
    if (name.equals("[dtd]")) {
350
      processingDTD = true;
351
    }
352
  }
353
354
  /**
355 688 bojilova
   * SAX Handler that receives notification of the end of entities.
356
   * @param name name of the entity
357 598 bojilova
   */
358
  public void endEntity(String name) throws SAXException {
359
    if (name.equals("[dtd]")) {
360
      processingDTD = false;
361
    }
362
  }
363
364
  /**
365 688 bojilova
   * Get the document name.
366 598 bojilova
   */
367
  public String getDocname() {
368
    return docname;
369
  }
370
371
  /**
372 688 bojilova
   * Get the document processing state.
373 598 bojilova
   */
374
  public boolean processingDTD() {
375
    return processingDTD;
376
  }
377
378 802 bojilova
  /* Get all objects associated with @aclid from db.*/
379
  private Vector getACLObjects(String aclid)
380 638 bojilova
          throws SQLException
381
  {
382 802 bojilova
    Vector aclObjects = new Vector();
383 645 bojilova
    // delete all acl records for resources related to @aclid if any
384 802 bojilova
    PreparedStatement pstmt = conn.prepareStatement(
385
                             "SELECT object FROM xml_relation " +
386 830 jones
                             "WHERE subject = ? ");
387 802 bojilova
    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 638 bojilova
  }
400
401 802 bojilova
  /* Delete from db all permission for resources related to @aclid if any.*/
402
  private void deletePermissionsForRelatedResources(String aclid)
403 638 bojilova
          throws SQLException
404
  {
405 802 bojilova
    // delete all acl records for resources related to @aclid if any
406 645 bojilova
    Statement stmt = conn.createStatement();
407 802 bojilova
    stmt.execute("DELETE FROM xml_access WHERE accessfileid = '" + aclid + "'");
408 645 bojilova
    stmt.close();
409
  }
410
411 688 bojilova
  /* Insert into db calculated permission for the list of principals */
412 802 bojilova
  private void insertPermissions(String docid, String permType )
413 555 bojilova
          throws SQLException
414
  {
415 672 bojilova
    PreparedStatement pstmt;
416 638 bojilova
417 555 bojilova
    try {
418
      pstmt = conn.prepareStatement(
419
              "INSERT INTO xml_access " +
420 645 bojilova
              "(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 555 bojilova
      // Bind the values to the query
424 802 bojilova
      pstmt.setString(1, docid);
425 570 bojilova
      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 645 bojilova
      pstmt.setString(9, aclid);
431 570 bojilova
      if ( ticketCount > 0 ) {
432
        pstmt.setString(8, "" + ticketCount);
433
      } else {
434 555 bojilova
        pstmt.setString(8, "");
435 570 bojilova
      }
436 802 bojilova
437 688 bojilova
      String prName;
438 802 bojilova
      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 688 bojilova
          }
452 802 bojilova
          throw new SQLException("Permission(s) " + txtValue(perm) +
453
                    " for \"" + prName + "\" on document #" + docid +
454
                    " has/have been used with \"" + permOrderOpos + "\"");
455 665 bojilova
        }
456 802 bojilova
      */
457 570 bojilova
      }
458 672 bojilova
      pstmt.close();
459 555 bojilova
460 570 bojilova
    } catch (SQLException e) {
461
      throw new
462
      SQLException("AccessControlList.insertPermissions(): " + e.getMessage());
463 672 bojilova
    }
464
  }
465
466 688 bojilova
  /* 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 765 bojilova
            "WHERE docid = ? " +
475
            "AND principal_name = ? " +
476
            "AND perm_order NOT = ?");
477 688 bojilova
    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 802 bojilova
  /**
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 688 bojilova
  {
541 802 bojilova
    // 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 688 bojilova
      }
553
    }
554 802 bojilova
    // Check for @permission for "public" user
555
    if ( !hasPermission ) {
556
      hasPermission = hasPermission(permission,"public",docid);
557
    }
558
559
    return hasPermission;
560
  }
561 688 bojilova
562
  /**
563 802 bojilova
    * Check from db connection if @principal has @permission on @docid.
564 688 bojilova
    * @param permission permission type to check for
565
    * @param principal name of principal to check for @permission
566 802 bojilova
    * @param docid document identifier to check on
567 688 bojilova
    */
568 802 bojilova
  private boolean hasPermission(String permission,
569
                                String principal, String docid)
570 570 bojilova
                 throws SQLException
571
  {
572
    PreparedStatement pstmt;
573 802 bojilova
    // check public access to @docid from xml_documents table
574 570 bojilova
    if ( permission.equals("READ") ) {
575
      try {
576 607 bojilova
        pstmt = conn.prepareStatement(
577 570 bojilova
                "SELECT 'x' FROM xml_documents " +
578 765 bojilova
                "WHERE docid = ? AND public_access = 1");
579 570 bojilova
        // Bind the values to the query
580 802 bojilova
        pstmt.setString(1, docid);
581 570 bojilova
582 555 bojilova
        pstmt.execute();
583 570 bojilova
        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 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
594 802 bojilova
                     "Error checking public access for document #"+docid+
595 688 bojilova
                     ". " + e.getMessage());
596 555 bojilova
      }
597 570 bojilova
    }
598
599
    // since owner of resource has all permission on it,
600 802 bojilova
    // check if @principal is owner of @docid in xml_documents table
601 570 bojilova
    if ( principal != null ) {
602
      try {
603 607 bojilova
        pstmt = conn.prepareStatement(
604 570 bojilova
                "SELECT 'x' FROM xml_documents " +
605 765 bojilova
                "WHERE docid = ? AND user_owner = ?");
606 570 bojilova
        // Bind the values to the query
607 802 bojilova
        pstmt.setString(1, docid);
608 570 bojilova
        pstmt.setString(2, principal);
609 555 bojilova
610 570 bojilova
        pstmt.execute();
611
        ResultSet rs = pstmt.getResultSet();
612
        boolean hasRow = rs.next();
613
        pstmt.close();
614
        if (hasRow) {
615
          return true;
616 555 bojilova
        }
617 570 bojilova
//System.out.println("Passed the check for ownership");
618
619
      } catch (SQLException e) {
620
        throw new
621 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
622
                     "Error checking ownership for " + principal +
623 802 bojilova
                     " on document #" + docid + ". " + e.getMessage());
624 570 bojilova
      }
625
626 802 bojilova
      // check @principal's @permission on @docid from xml_access table
627 570 bojilova
      int accessValue = 0;
628
      int ticketCount = 0;
629
      String permOrder = "";
630
      try {
631 607 bojilova
        pstmt = conn.prepareStatement(
632 570 bojilova
                "SELECT permission, perm_order, ticket_count " +
633
                "FROM xml_access " +
634 765 bojilova
                "WHERE docid = ? " +
635
                "AND principal_name = ? " +
636
                "AND perm_type = ? " +
637 774 bojilova
                "AND " + sysdate +
638
                " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
639
                     "AND " + isnull + "(end_time," + sysdate + ")");
640 688 bojilova
        // check if it is "deny" with "allowFirst" first
641 570 bojilova
        // Bind the values to the query
642 802 bojilova
        pstmt.setString(1, docid);
643 570 bojilova
        pstmt.setString(2, principal);
644 688 bojilova
        pstmt.setString(3, "deny");
645 570 bojilova
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 638 bojilova
               ( permOrder.equals("allowFirst") ) &&
655 570 bojilova
               ( rs.wasNull() || ticketCount > 0 ) ) {
656
            if ( !rs.wasNull() && ticketCount > 0 ) {
657 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","allowFirst");
658 570 bojilova
            }
659
            pstmt.close();
660
            return false;
661
          }
662
          hasRows = rs.next();
663 555 bojilova
        }
664 688 bojilova
//System.out.println("Passed the check for \"deny\" access with \"allowFirst\"");
665 555 bojilova
666 688 bojilova
        // it is not denied then check if it is "allow"
667 570 bojilova
        // Bind the values to the query
668 802 bojilova
        pstmt.setString(1, docid);
669 570 bojilova
        pstmt.setString(2, principal);
670 688 bojilova
        pstmt.setString(3, "allow");
671 570 bojilova
672 555 bojilova
        pstmt.execute();
673 570 bojilova
        rs = pstmt.getResultSet();
674
        hasRows = rs.next();
675
        while ( hasRows ) {
676
          accessValue = rs.getInt(1);
677 688 bojilova
          permOrder = rs.getString(2);
678 570 bojilova
          ticketCount = rs.getInt(3);
679
          if ( ( accessValue & intValue(permission) )==intValue(permission) &&
680
               ( rs.wasNull() || ticketCount > 0 ) ) {
681
            if ( !rs.wasNull() && ticketCount > 0 ) {
682 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"allow",permOrder);
683 570 bojilova
            }
684
            pstmt.close();
685
            return true;
686
          }
687
          hasRows = rs.next();
688
        }
689 688 bojilova
//System.out.println("Passed the check for \"allow\" access");
690 570 bojilova
691 688 bojilova
        // it is not allowed then check if it is "deny" with "denyFirst"
692
        // Bind the values to the query
693 802 bojilova
        pstmt.setString(1, docid);
694 688 bojilova
        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 802 bojilova
              decreaseNumberOfAccess(accessValue,principal,docid,"deny","denyFirst");
709 688 bojilova
            }
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 570 bojilova
717
        pstmt.close();
718
        return false;
719
720
      } catch (SQLException e) {
721
        throw new
722 688 bojilova
        SQLException("AccessControlList.hasPermission(). " +
723
                     "Error checking " + permission + " permission for " +
724 802 bojilova
                     principal + " on document #" + docid + ". " +
725 688 bojilova
                     e.getMessage());
726 555 bojilova
      }
727 570 bojilova
    }
728
729
    return false;
730
  }
731 555 bojilova
732 802 bojilova
  /* Decrease the number of access to @docid for @principal in db. */
733 570 bojilova
  private void decreaseNumberOfAccess(int permission, String principal,
734 802 bojilova
                                      String docid, String permType,
735 688 bojilova
                                      String permOrder)
736 570 bojilova
               throws SQLException
737
  {
738
    PreparedStatement pstmt;
739
    pstmt = conn.prepareStatement(
740
            "UPDATE xml_access SET ticket_count = ticket_count - 1 " +
741 765 bojilova
            "WHERE docid = ? " +
742
            "AND principal_name = ? " +
743
            "AND permission = ? " +
744
            "AND perm_type = ? " +
745
            "AND perm_order = ? " +
746 774 bojilova
            "AND " + sysdate +
747
            " BETWEEN " + isnull + "(begin_time," + sysdate + ") " +
748
                 "AND " + isnull + "(end_time," + sysdate + ")");
749 570 bojilova
    // Bind the values to the query
750 802 bojilova
    pstmt.setString(1, docid);
751 570 bojilova
    pstmt.setString(2, principal);
752
    pstmt.setInt(3, permission);
753
    pstmt.setString(4, permType);
754 688 bojilova
    pstmt.setString(5, permOrder);
755 570 bojilova
756
    pstmt.execute();
757
    pstmt.close();
758
  }
759
760 688 bojilova
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 802 bojilova
    * @param groups names of user's groups to which user belongs
768 688 bojilova
    */
769 802 bojilova
  public String getACL(String docid, String user, String[] groups)
770 688 bojilova
          throws SQLException
771 570 bojilova
  {
772 688 bojilova
    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 570 bojilova
783 688 bojilova
    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 638 bojilova
    try {
800 688 bojilova
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 765 bojilova
              "FROM xml_access WHERE docid = ? " +
816 688 bojilova
              "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 802 bojilova
        // access files to which @user/@groups has "read" permission
835 688 bojilova
        // is extracted
836
        if ( !isOwned ) {
837
          if ( !acfid.equals(acfid_prev) ) {
838
            acfid_prev = acfid;
839 802 bojilova
            hasPermission = this.hasPermission("READ",user,groups,acfid);
840 688 bojilova
          }
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 652 bojilova
      }
916 688 bojilova
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 638 bojilova
    }
940 688 bojilova
  }
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 765 bojilova
                                  "WHERE docid = ? " +
948
                                  "AND user_owner = ?");
949 688 bojilova
    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 652 bojilova
958 688 bojilova
  /* 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 765 bojilova
                                  "WHERE docid = ?");
965 688 bojilova
    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 765 bojilova
                                  "AND public_id = ?");
984 688 bojilova
    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 555 bojilova
}