KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > jdbc > JDBCPolicyDatabase


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.jdbc;
21
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.ObjectOutputStream JavaDoc;
25 import java.io.Serializable JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.sql.Timestamp JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.Calendar JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38
39 import org.apache.commons.cache.Cache;
40 import org.apache.commons.cache.CacheStat;
41 import org.apache.commons.cache.MemoryStash;
42 import org.apache.commons.cache.SimpleCache;
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45
46 import com.sslexplorer.boot.ContextHolder;
47 import com.sslexplorer.boot.PropertyList;
48 import com.sslexplorer.core.CoreEvent;
49 import com.sslexplorer.core.CoreEventConstants;
50 import com.sslexplorer.core.CoreListener;
51 import com.sslexplorer.core.CoreServlet;
52 import com.sslexplorer.core.UserDatabaseManager;
53 import com.sslexplorer.policyframework.AbstractPolicyDatabase;
54 import com.sslexplorer.policyframework.AccessRight;
55 import com.sslexplorer.policyframework.AccessRights;
56 import com.sslexplorer.policyframework.DefaultAccessRights;
57 import com.sslexplorer.policyframework.DefaultPolicy;
58 import com.sslexplorer.policyframework.Permission;
59 import com.sslexplorer.policyframework.Policy;
60 import com.sslexplorer.policyframework.PolicyConstants;
61 import com.sslexplorer.policyframework.Principal;
62 import com.sslexplorer.policyframework.Resource;
63 import com.sslexplorer.policyframework.ResourceAttachedToPolicyEvent;
64 import com.sslexplorer.policyframework.ResourceDetachedFromPolicyEvent;
65 import com.sslexplorer.policyframework.ResourceType;
66 import com.sslexplorer.realms.Realm;
67 import com.sslexplorer.security.LogonControllerFactory;
68 import com.sslexplorer.security.Role;
69 import com.sslexplorer.security.SessionInfo;
70 import com.sslexplorer.security.User;
71 import com.sslexplorer.security.UserDatabase;
72 import com.sslexplorer.security.UserNotFoundException;
73
74 /**
75  * Concrete implementation of a
76  * {@link com.sslexplorer.policyframework.PolicyDatabase} that stores policy
77  * information in a JDBC compliant database.
78  *
79  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
80  */

81 public class JDBCPolicyDatabase extends AbstractPolicyDatabase {
82     final static Log log = LogFactory.getLog(JDBCPolicyDatabase.class);
83
84     private JDBCDatabaseEngine db;
85
86     final static Long JavaDoc CACHE_TTL = new Long JavaDoc(System.getProperty(
87             "sslexplorer.jdbcPolicyDatabase.cacheTTL", "180000"));
88
89     final static Integer JavaDoc CACHE_MAXOBJS = new Integer JavaDoc(System.getProperty(
90             "sslexplorer.jdbcPolicyDatabase.cacheMaxObjs", "2000"));
91
92     final static Long JavaDoc CACHE_COST = new Long JavaDoc(0);
93
94     // Caches
95
private Cache policyCache;
96
97     /*
98      * (non-Javadoc)
99      *
100      * @see com.sslexplorer.policyframework.PolicyDatabase#getPolicy(int)
101      */

102     public Policy getPolicy(int id) throws Exception JavaDoc {
103         String JavaDoc cacheKey = "policy-" + id;
104         Policy pol = (Policy) policyCache.retrieve(cacheKey);
105         if (pol == null) {
106             // Get the top level policy
107
JDBCPreparedStatement ps = db.getStatement("getPolicy.selectById");
108             ps.setInt(1, id);
109             try {
110                 ResultSet JavaDoc rs = ps.executeQuery();
111                 if (rs.next()) {
112                     pol = buildPolicy(rs);
113                 }
114             } finally {
115                 ps.releasePreparedStatement();
116             }
117             if (pol != null) {
118                 storeToCache(cacheKey, (Serializable JavaDoc) pol);
119             }
120         }
121         return pol;
122     }
123
124     /* (non-Javadoc)
125      * @see com.sslexplorer.policyframework.PolicyDatabase#getPolicies(com.sslexplorer.realms.Realm)
126      */

127     public List JavaDoc<Policy> getPolicies(Realm realm) throws Exception JavaDoc {
128         String JavaDoc cacheKey = "policyByRealm-" + realm.getResourceId();
129         List JavaDoc<Policy> l = (List JavaDoc<Policy>) policyCache.retrieve(cacheKey);
130         if (l == null) {
131             // Get the top level policy
132
JDBCPreparedStatement ps = db.getStatement("getPolicy.selectByRealmId");
133             ps.setInt(1, realm.getResourceId());
134             l = new ArrayList JavaDoc<Policy>();
135             try {
136                 ResultSet JavaDoc rs = ps.executeQuery();
137                 while (rs.next()) {
138                     l.add(buildPolicy(rs));
139                 }
140             } finally {
141                 ps.releasePreparedStatement();
142             }
143             storeToCache(cacheKey, (Serializable JavaDoc) l);
144         }
145         return l;
146     }
147
148     /* (non-Javadoc)
149      * @see com.sslexplorer.policyframework.PolicyDatabase#getPolicies()
150      */

151     public List JavaDoc<Policy> getPolicies() throws Exception JavaDoc {
152         String JavaDoc cacheKey = "policies";
153         List JavaDoc<Policy> l = (List JavaDoc<Policy>) policyCache.retrieve(cacheKey);
154         if (l == null) {
155             // Get the top level policy
156
JDBCPreparedStatement ps = db.getStatement("getPolicies.select");
157             l = new ArrayList JavaDoc<Policy>();
158             try {
159                 ResultSet JavaDoc rs = ps.executeQuery();
160                 while (rs.next()) {
161                     l.add(buildPolicy(rs));
162                 }
163             } finally {
164                 ps.releasePreparedStatement();
165             }
166             storeToCache(cacheKey, (Serializable JavaDoc) l);
167         }
168         return l;
169     }
170
171     /* (non-Javadoc)
172      * @see com.sslexplorer.policyframework.PolicyDatabase#createPolicy(java.lang.String, java.lang.String, int, int)
173      */

174     public Policy createPolicy(String JavaDoc name, String JavaDoc description, int type, int realmID) throws Exception JavaDoc {
175         policyCache.clear();
176         JDBCPreparedStatement ps = db.getStatement("createPolicy.insert");
177         ps.startTransaction();
178         ps.setInt(1, type);
179         ps.setString(2, name);
180         ps.setString(3, description);
181         Calendar JavaDoc c = Calendar.getInstance();
182         ps.setString(4, db.formatTimestamp(c));
183         ps.setString(5, db.formatTimestamp(c));
184         ps.setInt(6, realmID);
185         try {
186             try {
187                 ps.execute();
188                 int id = db.getLastInsertId(ps, "createPolicy.lastInsertId");
189                 ps.commit();
190                 return new DefaultPolicy(id, name, description, type, c, c, realmID);
191             } finally {
192                 ps.releasePreparedStatement();
193             }
194         } catch (Exception JavaDoc e) {
195             ps.rollback();
196             throw e;
197         } finally {
198             ps.endTransaction();
199         }
200     }
201
202     /*
203      * (non-Javadoc)
204      *
205      * @see com.sslexplorer.policyframework.PolicyDatabase#updatePolicy(com.sslexplorer.policyframework.Policy)
206      */

207     public void updatePolicy(Policy policy) throws Exception JavaDoc {
208         Policy oldPolicy = getPolicy(policy.getResourceId());
209         if (oldPolicy == null) {
210             throw new Exception JavaDoc("Cannot update a policy that doesnt exist");
211         }
212         policyCache.clear();
213         JDBCPreparedStatement ps = db.getStatement("updatePolicy.update");
214         ps.setInt(1, policy.getType());
215         ps.setString(2, policy.getResourceName());
216         ps.setString(3, policy.getResourceDescription());
217         Calendar JavaDoc c = Calendar.getInstance();
218         ps.setString(4, db.formatTimestamp(c));
219         ps.setInt(5, policy.getResourceId());
220
221         try {
222             ps.execute();
223             policy.setDateAmended(c);
224         } finally {
225             ps.releasePreparedStatement();
226         }
227     }
228
229     public Policy deletePolicy(int id) throws Exception JavaDoc {
230         Policy oldPolicy = getPolicy(id);
231         if (oldPolicy == null) {
232             throw new Exception JavaDoc("Cannot delete a policy that doesnt exist");
233         }
234         policyCache.clear();
235         // Now delete this policy
236
JDBCPreparedStatement ps = db.getStatement("deletePolicy.delete");
237         ps.setInt(1, id);
238         try {
239             ps.execute();
240             ps = db.getStatement("deletePolicy.relationships1");
241             ps.setInt(1, id);
242             ps.execute();
243             ps = db.getStatement("deletePolicy.relationships2");
244             ps.setInt(1, id);
245             ps.execute();
246         } finally {
247             ps.releasePreparedStatement();
248         }
249         return oldPolicy;
250     }
251
252     /**
253      * Get if a principal has been graded a policy.
254      *
255      * @param policy policy
256      * @param principal principal
257      * @return granted
258      * @throws Exception on any error
259      */

260     private boolean isPolicyGrantedToPrincipal(Policy policy, Principal principal)
261             throws Exception JavaDoc {
262         if(principal==null) {
263             if(log.isInfoEnabled())
264                 log.info("NULL principal found!");
265             return false;
266         }
267         if (policy.getResourceId() == getEveryonePolicyIDForRealm(principal.getRealm())) {
268             return true;
269         }
270         String JavaDoc cacheKey = "policyGrantedToPrincipal-" + policy.getResourceId()
271                 + "-" + principal.getPrincipalName() + "-" + principal.getRealm().getResourceId();
272         Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
273         if (val == null) {
274             JDBCPreparedStatement ps = db
275                     .getStatement("isPolicyGrantedToPrincipal.select");
276             ps.setInt(1, policy.getResourceId());
277             ps.setString(2, principal.getPrincipalName());
278             boolean found = false;
279             try {
280                 ResultSet JavaDoc rs = ps.executeQuery();
281                 try {
282                     found = rs.next();
283                 } finally {
284                     rs.close();
285                 }
286             } finally {
287                 ps.releasePreparedStatement();
288             }
289             storeToCache(cacheKey, Boolean.valueOf(found));
290             val = Boolean.valueOf(found);
291         }
292         return val.booleanValue();
293     }
294
295     /*
296      * (non-Javadoc)
297      *
298      * @see com.sslexplorer.policyframework.PolicyDatabase#grantPolicyToPrincipal(com.sslexplorer.policyframework.Policy,
299      * com.sslexplorer.permissions.Principal)
300      */

301     public void grantPolicyToPrincipal(Policy policy, Principal principal)
302             throws Exception JavaDoc {
303         if (policy.getResourceId() == getEveryonePolicyIDForRealm(principal.getRealm())) {
304             throw new Exception JavaDoc(
305                     "Cannot grant special Everyone policy to any principal, it is granted by default.");
306         }
307         policyCache.clear();
308         JDBCPreparedStatement ps = db
309                 .getStatement("grantPolicyToPrincipal.insert");
310         ps.setInt(1, policy.getResourceId());
311         ps.setString(2, principal.getPrincipalName());
312         ps.setInt(3, (principal instanceof User) ? Policy.PRINCIPAL_USER
313                 : Policy.PRINCIPAL_GROUP);
314         try {
315             ps.execute();
316         } finally {
317             ps.releasePreparedStatement();
318         }
319     }
320
321     /*
322      * (non-Javadoc)
323      *
324      * @see com.sslexplorer.policyframework.PolicyDatabase#revokePolicyFromPrincipal(com.sslexplorer.policyframework.Policy,
325      * com.sslexplorer.permissions.Principal)
326      */

327     public void revokePolicyFromPrincipal(Policy policy, Principal principal)
328             throws Exception JavaDoc {
329         if (policy.getResourceId() == getEveryonePolicyIDForRealm(principal.getRealm())) {
330             throw new Exception JavaDoc(
331                     "Cannot revoke special Everyone policy from any principal.");
332         }
333         policyCache.clear();
334         JDBCPreparedStatement ps = db
335                 .getStatement("revokePolicyFromPrincipal.delete");
336         ps.setInt(1, policy.getResourceId());
337         ps.setString(2, principal.getPrincipalName());
338         ps.setInt(3, (principal instanceof User) ? Policy.PRINCIPAL_USER
339                 : Policy.PRINCIPAL_GROUP);
340         try {
341             ps.execute();
342         } finally {
343             ps.releasePreparedStatement();
344         }
345     }
346
347     /*
348      * (non-Javadoc)
349      *
350      * @see com.sslexplorer.policyframework.PolicyDatabase#revokeAllPoliciesFromPrincipal(com.sslexplorer.permissions.Principal)
351      */

352     public void revokeAllPoliciesFromPrincipal(Principal principal)
353             throws Exception JavaDoc {
354         policyCache.clear();
355         JDBCPreparedStatement ps = db
356                 .getStatement("revokeAllPoliciesFromPrincipal.delete");
357         ps.setString(1, principal.getPrincipalName());
358         try {
359             ps.execute();
360         } finally {
361             ps.releasePreparedStatement();
362         }
363
364     }
365
366     /* (non-Javadoc)
367      * @see com.sslexplorer.policyframework.PolicyDatabase#attachResourceToPolicy(com.sslexplorer.policyframework.Resource, com.sslexplorer.policyframework.Policy, int)
368      */

369     public void attachResourceToPolicy(Resource resource, Policy policy, int sequence, Realm realm)
370             throws Exception JavaDoc {
371         policyCache.clear();
372         JDBCPreparedStatement ps = db
373                 .getStatement("attachResourceToPolicy.insert");
374         ps.setInt(1, resource.getResourceId());
375         ps.setInt(2, resource.getResourceType().getResourceTypeId());
376         ps.setInt(3, policy.getResourceId());
377         ps.setInt(4, sequence);
378         ps.setInt(5, realm.getResourceId());
379         try {
380             ps.execute();
381         } finally {
382             ps.releasePreparedStatement();
383         }
384     }
385
386     /*
387      * (non-Javadoc)
388      *
389      * @see com.sslexplorer.policyframework.PolicyDatabase#detachResourceFromPolicy(com.sslexplorer.policyframework.Resource,
390      * com.sslexplorer.policyframework.Policy)
391      */

392     public void detachResourceFromPolicy(Resource resource, Policy policy, Realm realm)
393             throws Exception JavaDoc {
394         policyCache.clear();
395         JDBCPreparedStatement ps = db
396                 .getStatement("detachResourceFromPolicy.delete");
397         ps.setInt(1, resource.getResourceId());
398         ps.setInt(2, resource.getResourceType().getResourceTypeId());
399         ps.setInt(3, policy.getResourceId());
400         ps.setInt(4, realm.getResourceId());
401         try {
402             ps.execute();
403         } finally {
404             ps.releasePreparedStatement();
405         }
406     }
407
408     /*
409      * (non-Javadoc)
410      *
411      * @see com.sslexplorer.policyframework.PolicyDatabase#isResourceAttachedToPolicy(com.sslexplorer.policyframework.Resource,
412      * com.sslexplorer.policyframework.Policy)
413      */

414     public boolean isResourceAttachedToPolicy(Resource resource, Policy policy, Realm realm)
415             throws Exception JavaDoc {
416         String JavaDoc cacheKey = "resourcePolicy-" + resource.getResourceId() + "-"
417                 + resource.getResourceType().getResourceTypeId() + "-"
418                 + policy.getResourceId();
419         Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
420         if (val == null) {
421             JDBCPreparedStatement ps = db
422                     .getStatement("isResourceAttachedToPolicy.select");
423             ps.setInt(1, resource.getResourceId());
424             ps.setInt(2, resource.getResourceType().getResourceTypeId());
425             ps.setInt(3, policy.getResourceId());
426             ps.setInt(4, realm.getResourceId());
427             try {
428                 ResultSet JavaDoc rs = ps.executeQuery();
429                 try {
430                     val = new Boolean JavaDoc(rs.next());
431                 } finally {
432                     rs.close();
433                 }
434             } finally {
435                 ps.releasePreparedStatement();
436             }
437             storeToCache(cacheKey, val);
438         }
439         return val.booleanValue();
440     }
441
442
443     /* (non-Javadoc)
444      * @see com.sslexplorer.policyframework.PolicyDatabase#isPrincipalAllowed(com.sslexplorer.policyframework.Principal, com.sslexplorer.policyframework.Resource, boolean)
445      */

446     public boolean isPrincipalAllowed(Principal principal, Resource resource,
447             boolean includeSuperUser) throws Exception JavaDoc {
448
449         String JavaDoc cacheKey = "principalAllowed-" + principal.getPrincipalName() + "-realmID-" + principal.getRealm().getResourceId()
450                 + "-" + resource.getResourceId() + "-"
451                 + resource.getResourceType().getResourceTypeId() + "-"
452                 + includeSuperUser;
453         Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
454         if (val == null) {
455
456             if (principal instanceof User && includeSuperUser) {
457                 if (LogonControllerFactory.getInstance()
458                         .isAdministrator((User) principal)) {
459                     val = Boolean.TRUE;
460                     storeToCache(cacheKey, val);
461                     return val.booleanValue();
462                 }
463             }
464             
465             Policy p = getGrantingPolicy(principal, resource);
466             val = p == null ? Boolean.FALSE : Boolean.TRUE;
467
468             storeToCache(cacheKey, val);
469         }
470         return val.booleanValue();
471     }
472     
473     /*
474      * (non-Javadoc)
475      *
476      * @see com.sslexplorer.boot.Database#cleanup()
477      */

478     public void cleanup() throws Exception JavaDoc {
479         policyCache.clear();
480     }
481
482     /*
483      * (non-Javadoc)
484      *
485      * @see com.sslexplorer.boot.Database#open(javax.servlet.ServletContext)
486      */

487     public void open(CoreServlet controllingServlet) throws Exception JavaDoc {
488         String JavaDoc dbName = System.getProperty(
489                 "sslexplorer.policyyDatabase.jdbc.dbName",
490                 "explorer_configuration");
491         controllingServlet.addDatabase(dbName, ContextHolder.getContext().getDBDirectory());
492         String JavaDoc jdbcUser = System.getProperty("sslexplorer.jdbc.username", "sa");
493         String JavaDoc jdbcPassword = System.getProperty("sslexplorer.jdbc.password",
494                 "");
495         String JavaDoc vendorDB = System.getProperty("sslexplorer.jdbc.vendorClass",
496                 "com.sslexplorer.jdbc.hsqldb.HSQLDBDatabaseEngine");
497         if (log.isInfoEnabled()) {
498             log.info("Policy database is being opened...");
499             log.info("JDBC vendor class implementation is " + vendorDB);
500         }
501         File JavaDoc upgradeDir = new File JavaDoc("install/upgrade");
502         db = (JDBCDatabaseEngine) Class.forName(vendorDB).newInstance();
503         db.init("policyDatabase", dbName, jdbcUser, jdbcPassword, null);
504         DBUpgrader upgrader = new DBUpgrader(ContextHolder.getContext()
505                 .getVersion(), db, ContextHolder.getContext().getDBDirectory(),
506                 upgradeDir);
507         upgrader.upgrade();
508         policyCache = new SimpleCache(new MemoryStash(CACHE_MAXOBJS.intValue()));
509         CoreServlet.getServlet().addCoreListener(new CoreListener() {
510             public void coreEvent(CoreEvent evt) {
511                 if (evt.getId() == CoreEventConstants.USER_CREATED
512                         || evt.getId() == CoreEventConstants.USER_EDITED
513                         || evt.getId() == CoreEventConstants.USER_REMOVED
514                         || evt.getId() == CoreEventConstants.GROUP_CREATED
515                         || evt.getId() == CoreEventConstants.GROUP_REMOVED) {
516                     policyCache.clear();
517                 }
518             }
519         });
520     }
521
522     /*
523      * (non-Javadoc)
524      *
525      * @see com.sslexplorer.boot.Database#close()
526      */

527     public void close() throws Exception JavaDoc {
528     }
529
530     /*
531      * (non-Javadoc)
532      *
533      * @see com.sslexplorer.policyframework.PolicyDatabase#getPoliciesAttachedToResource(com.sslexplorer.boot.policyframework.Resource)
534      */

535     public List JavaDoc<Policy> getPoliciesAttachedToResource(Resource resource, Realm realm)
536             throws Exception JavaDoc {
537         String JavaDoc cacheKey = "resourcePolicies-" + resource.getResourceId() + "-"
538                 + resource.getResourceType().getResourceTypeId() + "-realmID-" + realm.getResourceId();
539         List JavaDoc<Policy> l = (List JavaDoc<Policy>) policyCache.retrieve(cacheKey);
540         if (l == null) {
541
542             // Get the top level policy
543
JDBCPreparedStatement ps = db
544                     .getStatement("getPoliciesAttachedToResource.select");
545             ps.setInt(1, resource.getResourceId());
546             ps.setInt(2, resource.getResourceType().getResourceTypeId());
547             ps.setInt(3, realm.getResourceId());
548             l = new ArrayList JavaDoc<Policy>();
549             try {
550                 ResultSet JavaDoc rs = ps.executeQuery();
551                 while (rs.next()) {
552                     l.add(buildPolicy(rs));
553                 }
554                 storeToCache(cacheKey, (Serializable JavaDoc) l);
555             } finally {
556                 ps.releasePreparedStatement();
557             }
558         }
559         return l;
560     }
561
562     /* (non-Javadoc)
563      * @see com.sslexplorer.policyframework.PolicyDatabase#getPrincipalsGrantedPolicy(com.sslexplorer.policyframework.Policy, com.sslexplorer.realms.Realm)
564      */

565     public List JavaDoc<Principal> getPrincipalsGrantedPolicy(Policy policy, Realm realm) throws Exception JavaDoc {
566         String JavaDoc cacheKey = "policyPrincipals-" + policy.getResourceId();
567         List JavaDoc<Principal> l = (List JavaDoc<Principal>) policyCache.retrieve(cacheKey);
568         if (l == null) {
569             l = new ArrayList JavaDoc<Principal>();
570             UserDatabase udb = UserDatabaseManager.getInstance().getUserDatabase(realm);
571             if (policy.getResourceId() == getEveryonePolicyIDForRealm(realm)) {
572                 l.addAll(Arrays.asList(udb.listAllUsers("*")));
573                 l.addAll(Arrays.asList(udb.listAllRoles("*")));
574             } else {
575                 JDBCPreparedStatement ps = db
576                         .getStatement("getPrincipalsGrantedPolicy.select");
577                 ps.setInt(1, policy.getResourceId());
578                 try {
579                     ResultSet JavaDoc rs = ps.executeQuery();
580                     while (rs.next()) {
581                         String JavaDoc principalId = rs.getString("principal_id");
582                         int princpalType = rs.getInt("principal_type");
583                         Principal p = null;
584                         if (princpalType == Policy.PRINCIPAL_USER) {
585                             try {
586                                 p = udb.getAccount(principalId);
587                             }
588                             catch(UserNotFoundException unfe) {
589                                 // User no longer exists, just place a warning in the logs
590
}
591                         } else {
592                             p = udb.getRole(principalId);
593                         }
594                         if (p == null) {
595                             log
596                                     .warn("An invalid principal is attached to policy "
597                                             + policy.getResourceId()
598                                             + ". This may happen if you switch user databases or remove users from an external userdatabase. Ignoring.");
599                         } else {
600                             l.add(p);
601                         }
602                     }
603                 } finally {
604                     ps.releasePreparedStatement();
605                 }
606             }
607             storeToCache(cacheKey, (Serializable JavaDoc) l);
608         }
609         return l;
610     }
611
612     /* (non-Javadoc)
613      * @see com.sslexplorer.policyframework.PolicyDatabase#revokePolicyFromAllPrincipals(com.sslexplorer.policyframework.Policy, com.sslexplorer.realms.Realm)
614      */

615     public void revokePolicyFromAllPrincipals(Policy policy, Realm realm) throws Exception JavaDoc {
616         if (policy.getResourceId() == getEveryonePolicyIDForRealm(realm)) {
617             throw new Exception JavaDoc(
618                     "Cannot revoke special Everyone policy from all principals.");
619         }
620         policyCache.clear();
621         JDBCPreparedStatement ps2 = db
622                 .getStatement("revokePolicyFromAllPrincipals.delete");
623         ps2.setInt(1, policy.getResourceId());
624         try {
625             ps2.execute();
626         } finally {
627             ps2.releasePreparedStatement();
628         }
629     }
630
631     /*
632      * (non-Javadoc)
633      *
634      * @see com.sslexplorer.policyframework.PolicyDatabase#createResourcePermission(com.sslexplorer.policyframework.ResourcePermission)
635      */

636     public AccessRights createAccessRights(
637             AccessRights resourcePermission) throws Exception JavaDoc {
638         policyCache.clear();
639         JDBCPreparedStatement ps = db
640                 .getStatement("createResourcePermission.insert");
641         ps.startTransaction();
642         ps.setString(1, resourcePermission.getResourceName());
643         ps.setString(2, resourcePermission.getAccessRightsClass());
644         ps.setString(3, resourcePermission.getResourceDescription());
645         Calendar JavaDoc c = Calendar.getInstance();
646         ps.setString(4, db.formatTimestamp(c));
647         ps.setString(5, db.formatTimestamp(c));
648         ps.setInt(6, resourcePermission.getRealmID());
649         try {
650             try {
651                 ps.execute();
652                 int id = db.getLastInsertId(ps,
653                         "createResourcePermission.lastInsertId");
654                 resourcePermission.setResourceId(id);
655                 updateResourcePermissionRelationships(ps, resourcePermission);
656                 ps.commit();
657                 return resourcePermission;
658             } finally {
659                 ps.releasePreparedStatement();
660             }
661         } catch (Exception JavaDoc e) {
662             ps.rollback();
663             throw e;
664         } finally {
665             ps.endTransaction();
666         }
667     }
668
669     /*
670      * (non-Javadoc)
671      *
672      * @see com.sslexplorer.policyframework.PolicyDatabase#getResourcePermissions()
673      */

674     public List JavaDoc<AccessRights> getAccessRights() throws Exception JavaDoc {
675         String JavaDoc cacheKey = "resourcePermissions";
676         List JavaDoc<AccessRights> val = (List JavaDoc<AccessRights>) policyCache.retrieve(cacheKey);
677         if (val == null) {
678             JDBCPreparedStatement ps = db
679                     .getStatement("getResourcePermissions.select");
680             try {
681                 ResultSet JavaDoc rs = ps.executeQuery();
682                 val = buildResourcePermission(rs);
683             } finally {
684                 ps.releasePreparedStatement();
685             }
686         }
687         
688         return val;
689     }
690
691     /* (non-Javadoc)
692      * @see com.sslexplorer.policyframework.PolicyDatabase#getPolicyByName(java.lang.String, int)
693      */

694     public Policy getPolicyByName(String JavaDoc name, int realmID) throws Exception JavaDoc {
695         String JavaDoc cacheKey = "policyByName-" + name;
696         Policy pol = (Policy) policyCache.retrieve(cacheKey);
697         if (pol == null) {
698             JDBCPreparedStatement ps = db
699                     .getStatement("getPolicyByName.selectByName");
700             ps.setString(1, name);
701             ps.setInt(2, realmID);
702             try {
703                 ResultSet JavaDoc rs = ps.executeQuery();
704                 if (rs.next()) {
705                     pol = buildPolicy(rs);
706                 }
707             } finally {
708                 ps.releasePreparedStatement();
709             }
710             if (pol != null) {
711                 storeToCache(cacheKey, pol);
712             }
713         }
714         return pol;
715     }
716
717     /* (non-Javadoc)
718      * @see com.sslexplorer.policyframework.PolicyDatabase#getAccessRightsByName(java.lang.String, int)
719      */

720     public AccessRights getAccessRightsByName(String JavaDoc name, int realmID)
721             throws Exception JavaDoc {
722         String JavaDoc cacheKey = "resourcePermissionByName-" + name + "-realm id-" + realmID;
723         AccessRights resourcePermission = (AccessRights) policyCache
724                 .retrieve(cacheKey);
725         if (resourcePermission == null) {
726             JDBCPreparedStatement ps = db
727                     .getStatement("getResourcePermissionByName.select");
728             ps.setString(1, name);
729             ps.setInt(2, realmID);
730             try {
731                 ResultSet JavaDoc rs = ps.executeQuery();
732                 List JavaDoc l = buildResourcePermission(rs);
733                 if (l.size() > 0) {
734                     resourcePermission = (AccessRights) l.get(0);
735                 }
736             } finally {
737                 ps.releasePreparedStatement();
738             }
739             if (resourcePermission != null) {
740                 storeToCache(cacheKey, resourcePermission);
741             }
742         }
743         return resourcePermission;
744     }
745
746     /*
747      * (non-Javadoc)
748      *
749      * @see com.sslexplorer.policyframework.PolicyDatabase#getResourcePermission(int)
750      */

751     public AccessRights getAccessRight(int id) throws Exception JavaDoc {
752         String JavaDoc cacheKey = "resourcePermission-" + id;
753         AccessRights resourcePermission = (AccessRights) policyCache
754                 .retrieve(cacheKey);
755         if (resourcePermission == null) {
756             JDBCPreparedStatement ps = db
757                     .getStatement("getResourcePermission.select");
758             ps.setInt(1, id);
759             try {
760                 ResultSet JavaDoc rs = ps.executeQuery();
761                 List JavaDoc l = buildResourcePermission(rs);
762                 if (l.size() > 0) {
763                     resourcePermission = (AccessRights) l.get(0);
764                 }
765             } finally {
766                 ps.releasePreparedStatement();
767             }
768             if (resourcePermission != null) {
769                 storeToCache(cacheKey, resourcePermission);
770             }
771         }
772         return resourcePermission;
773     }
774
775     /* (non-Javadoc)
776      * @see com.sslexplorer.policyframework.PolicyDatabase#isAnyAccessRightAllowed(com.sslexplorer.security.User, boolean, boolean, boolean)
777      */

778     public boolean isAnyAccessRightAllowed(User user,
779             boolean delegation, boolean system, boolean personal)
780             throws Exception JavaDoc {
781         String JavaDoc cacheKey = "anyResourcePermissionAllowed-"
782                 + (user == null ? "" : user.getPrincipalName()) + "-"
783                 + delegation + "-" + system + "-" + personal;
784         Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
785         if (val == null) {
786             if (LogonControllerFactory.getInstance().isAdministrator(
787                     user)) {
788                 val = Boolean.TRUE;
789             } else {
790                 List JavaDoc resourcePermissions = getAccessRights();
791                 AccessRights resourcePermission = null;
792                 for (Iterator JavaDoc i = resourcePermissions.iterator(); val == null
793                         && i.hasNext();) {
794                     resourcePermission = (AccessRights) i.next();
795                     if (system
796                             && resourcePermission.getAccessRightsClass().equals(
797                                     PolicyConstants.SYSTEM_CLASS)
798                             || delegation
799                             && resourcePermission.getAccessRightsClass().equals(
800                                     PolicyConstants.DELEGATION_CLASS)
801                             || personal
802                             && resourcePermission.getAccessRightsClass().equals(
803                                     PolicyConstants.PERSONAL_CLASS))
804                         if (isPrincipalAllowed(user, resourcePermission, true)) {
805                             val = Boolean.TRUE;
806                         }
807                 }
808                 if (val == null) {
809                     val = Boolean.FALSE;
810                 }
811             }
812             storeToCache(cacheKey, val);
813         }
814         return val.booleanValue();
815     }
816
817     /* (non-Javadoc)
818      * @see com.sslexplorer.policyframework.PolicyDatabase#isPermitted(com.sslexplorer.policyframework.ResourceType, com.sslexplorer.policyframework.Permission[], com.sslexplorer.security.User, boolean)
819      */

820     public boolean isPermitted(ResourceType resourceType,
821             Permission[] requiredPermissions, User user, boolean all)
822             throws Exception JavaDoc {
823         StringBuffer JavaDoc buf = new StringBuffer JavaDoc("resourcePermissionAllowed-");
824         buf.append(resourceType.getResourceTypeId());
825         buf.append("-");
826         if(requiredPermissions != null) {
827             for (int i = 0; i < requiredPermissions.length; i++) {
828                 buf.append(requiredPermissions[i].getId());
829                 buf.append("-");
830             }
831         }
832         buf.append(user == null ? "" : user.getPrincipalName());
833         buf.append("-");
834         buf.append(String.valueOf(all));
835         String JavaDoc cacheKey = buf.toString();
836         Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
837         if (val == null) {
838             if (LogonControllerFactory.getInstance().isAdministrator(
839                     user)) {
840                 val = Boolean.TRUE;
841             } else {
842                 List JavaDoc resourcePermissions = getAccessRights();
843                 AccessRights resourcePermission = null;
844                 AccessRight permission = null;
845                 // Iterator through all resource permissions
846
Map JavaDoc<String JavaDoc,Boolean JavaDoc> matched = new HashMap JavaDoc<String JavaDoc,Boolean JavaDoc>();
847                 for (Iterator JavaDoc i = resourcePermissions.iterator(); val == null
848                         && i.hasNext();) {
849                     resourcePermission = (AccessRights) i.next();
850                     // Iterator through all permissions in the resource
851
for (Iterator JavaDoc j = resourcePermission.getAccessRights()
852                             .iterator(); val == null && j.hasNext();) {
853                         permission = (AccessRight) j.next();
854                         // Until the resource type matches
855
if (resourceType.equals(permission.getResourceType())) {
856                             // Check the mask, at least one must match
857
for (int x = 0; x < requiredPermissions.length; x++) {
858                                 if (permission.getPermission().getId() == requiredPermissions[x]
859                                         .getId()) {
860                                     // Check if the user in a policy
861
if (isPrincipalAllowed(user,
862                                             resourcePermission, true)) {
863                                         String JavaDoc key = String
864                                                 .valueOf(requiredPermissions[x]
865                                                         .getId());
866                                         matched.put(key, Boolean.TRUE);
867                                         if (!all
868                                                 || matched.size() == requiredPermissions.length) {
869                                             break;
870                                         }
871                                     }
872                                 }
873                             }
874                         }
875                     }
876                 }
877                 if (all && matched.size() == requiredPermissions.length) {
878                     val = Boolean.TRUE;
879                 } else if (!all && matched.size() > 0) {
880                     val = Boolean.TRUE;
881                 } else {
882                     val = Boolean.FALSE;
883                 }
884             }
885             storeToCache(cacheKey, val);
886         }
887         return val.booleanValue();
888     }
889
890     /*
891      * (non-Javadoc)
892      *
893      * @see com.sslexplorer.policyframework.PolicyDatabase#deleteResourcePermission(int)
894      */

895     public AccessRights deleteAccessRights(int id) throws Exception JavaDoc {
896         policyCache.clear();
897         AccessRights dr = getAccessRight(id);
898         if (dr == null) {
899             throw new Exception JavaDoc(
900                     "Cannot delete a resource permission that doesnt exist");
901         }
902         JDBCPreparedStatement ps = db
903                 .getStatement("deleteResourcePermission.delete");
904         ps.startTransaction();
905         ps.setInt(1, id);
906         try {
907             try {
908                 ps.execute();
909                 deleteResourcePermissionRelationships(ps, id);
910                 ps = db.getStatement(ps,
911                         "deleteResourcePermission.policyRelationship");
912                 ps.setInt(1, id);
913                 ps.setInt(2, dr.getResourceType().getResourceTypeId());
914                 ps.execute();
915                 ps.commit();
916             } finally {
917                 ps.releasePreparedStatement();
918             }
919         } catch (Exception JavaDoc e) {
920             ps.rollback();
921             throw e;
922         } finally {
923             ps.endTransaction();
924         }
925         return dr;
926     }
927
928     /*
929      * (non-Javadoc)
930      *
931      * @see com.sslexplorer.policyframework.PolicyDatabase#updateResourcePermission(com.sslexplorer.policyframework.ResourcePermission)
932      */

933     public void updateAccessRights(AccessRights resourcePermission)
934             throws Exception JavaDoc {
935         policyCache.clear();
936         JDBCPreparedStatement ps = db
937                 .getStatement("updateResourcePermission.update");
938         ps.startTransaction();
939         ps.setString(1, resourcePermission.getResourceName());
940         ps.setString(2, resourcePermission.getResourceDescription());
941         Calendar JavaDoc c = Calendar.getInstance();
942         ps.setString(3, db.formatTimestamp(c));
943         ps.setInt(4, resourcePermission.getResourceId());
944
945         try {
946             try {
947                 ps.execute();
948                 updateResourcePermissionRelationships(ps, resourcePermission);
949             } finally {
950                 ps.releasePreparedStatement();
951             }
952             ps.commit();
953             resourcePermission.setDateAmended(c);
954         } catch (Exception JavaDoc e) {
955             ps.rollback();
956             throw e;
957         } finally {
958             ps.endTransaction();
959         }
960     }
961
962     /*
963      * (non-Javadoc)
964      *
965      * @see com.sslexplorer.policyframework.PolicyDatabase#initResourcePermissions()
966      */

967     public void initAccessRights() throws Exception JavaDoc {
968         
969         // Has no permission
970
registerResourceType(PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE);
971         PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE.addPermission(PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN);
972         PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE.addPermission(PolicyConstants.PERM_EDIT_AND_ASSIGN);
973         PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE.addPermission(PolicyConstants.PERM_ASSIGN);
974         PolicyConstants.ACCESS_RIGHTS_RESOURCE_TYPE.addPermission(PolicyConstants.PERM_DELETE);
975
976         // -- Resource Permissions
977

978
979         // Policy
980
registerResourceType(PolicyConstants.POLICY_RESOURCE_TYPE);
981         PolicyConstants.POLICY_RESOURCE_TYPE
982                 .addPermission(PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN);
983         PolicyConstants.POLICY_RESOURCE_TYPE
984                 .addPermission(PolicyConstants.PERM_EDIT_AND_ASSIGN);
985         PolicyConstants.POLICY_RESOURCE_TYPE
986                 .addPermission(PolicyConstants.PERM_DELETE);
987         PolicyConstants.POLICY_RESOURCE_TYPE
988                 .addPermission(PolicyConstants.PERM_ASSIGN);
989
990         // Profile
991
registerResourceType(PolicyConstants.PROFILE_RESOURCE_TYPE);
992         PolicyConstants.PROFILE_RESOURCE_TYPE
993                 .addPermission(PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN);
994         PolicyConstants.PROFILE_RESOURCE_TYPE
995                 .addPermission(PolicyConstants.PERM_EDIT_AND_ASSIGN);
996         PolicyConstants.PROFILE_RESOURCE_TYPE
997                 .addPermission(PolicyConstants.PERM_DELETE);
998         PolicyConstants.PROFILE_RESOURCE_TYPE
999                 .addPermission(PolicyConstants.PERM_ASSIGN);
1000
1001        // -- System Resource Permissions
1002

1003        // Shutdown
1004
registerResourceType(PolicyConstants.SERVICE_CONTROL_RESOURCE_TYPE);
1005        PolicyConstants.SERVICE_CONTROL_RESOURCE_TYPE
1006                .addPermission(PolicyConstants.PERM_SHUTDOWN);
1007        PolicyConstants.SERVICE_CONTROL_RESOURCE_TYPE
1008                .addPermission(PolicyConstants.PERM_RESTART);
1009
1010        // System Configuration
1011
registerResourceType(PolicyConstants.SYSTEM_CONFIGURATION_RESOURCE_TYPE);
1012        PolicyConstants.SYSTEM_CONFIGURATION_RESOURCE_TYPE
1013                .addPermission(PolicyConstants.PERM_CHANGE);
1014
1015        // Keystore
1016
registerResourceType(PolicyConstants.KEYSTORE_RESOURCE_TYPE);
1017        PolicyConstants.KEYSTORE_RESOURCE_TYPE
1018                .addPermission(PolicyConstants.PERM_CHANGE);
1019
1020        // Authentication Schemes
1021
registerResourceType(PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE);
1022        PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE
1023                .addPermission(PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN);
1024        PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE
1025                .addPermission(PolicyConstants.PERM_EDIT_AND_ASSIGN);
1026        PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE
1027                .addPermission(PolicyConstants.PERM_ASSIGN);
1028        PolicyConstants.AUTHENTICATION_SCHEMES_RESOURCE_TYPE
1029                .addPermission(PolicyConstants.PERM_DELETE);
1030
1031        // Accounts
1032
registerResourceType(PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE);
1033        PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE
1034                .addPermission(PolicyConstants.PERM_CREATE_EDIT_AND_ASSIGN);
1035        PolicyConstants.ACCOUNTS_AND_GROUPS_RESOURCE_TYPE
1036                .addPermission(PolicyConstants.PERM_DELETE);
1037
1038        // IP Restrictions
1039
registerResourceType(PolicyConstants.IP_RESTRICTIONS_RESOURCE_TYPE);
1040        PolicyConstants.IP_RESTRICTIONS_RESOURCE_TYPE
1041                .addPermission(PolicyConstants.PERM_CREATE);
1042        PolicyConstants.IP_RESTRICTIONS_RESOURCE_TYPE
1043                .addPermission(PolicyConstants.PERM_DELETE);
1044        PolicyConstants.IP_RESTRICTIONS_RESOURCE_TYPE
1045                .addPermission(PolicyConstants.PERM_EDIT);
1046
1047        // Extensions
1048
registerResourceType(PolicyConstants.EXTENSIONS_RESOURCE_TYPE);
1049        PolicyConstants.EXTENSIONS_RESOURCE_TYPE.addPermission(PolicyConstants.PERM_CHANGE);
1050
1051        // Message Queue
1052
registerResourceType(PolicyConstants.MESSAGE_QUEUE_RESOURCE_TYPE);
1053        PolicyConstants.MESSAGE_QUEUE_RESOURCE_TYPE
1054                .addPermission(PolicyConstants.PERM_VIEW);
1055        PolicyConstants.MESSAGE_QUEUE_RESOURCE_TYPE
1056                .addPermission(PolicyConstants.PERM_CLEAR);
1057        PolicyConstants.MESSAGE_QUEUE_RESOURCE_TYPE
1058                .addPermission(PolicyConstants.PERM_CONTROL);
1059        PolicyConstants.MESSAGE_QUEUE_RESOURCE_TYPE
1060                .addPermission(PolicyConstants.PERM_SEND);
1061
1062        // Status
1063
registerResourceType(PolicyConstants.STATUS_TYPE_RESOURCE_TYPE);
1064        PolicyConstants.STATUS_TYPE_RESOURCE_TYPE
1065                .addPermission(PolicyConstants.PERM_VIEW);
1066
1067        // Replacement
1068
registerResourceType(PolicyConstants.REPLACEMENTS_RESOURCE_TYPE);
1069        PolicyConstants.REPLACEMENTS_RESOURCE_TYPE
1070                .addPermission(PolicyConstants.PERM_CHANGE);
1071
1072        // Attributes
1073
registerResourceType(PolicyConstants.ATTRIBUTE_DEFINITIONS_RESOURCE_TYPE);
1074        PolicyConstants.ATTRIBUTE_DEFINITIONS_RESOURCE_TYPE
1075                .addPermission(PolicyConstants.PERM_MAINTAIN);
1076        registerResourceType(PolicyConstants.ATTRIBUTES_RESOURCE_TYPE);
1077        PolicyConstants.ATTRIBUTES_RESOURCE_TYPE
1078                .addPermission(PolicyConstants.PERM_MAINTAIN);
1079
1080        // -- Personal Resource Permissions
1081

1082        // Profile
1083
registerResourceType(PolicyConstants.PERSONAL_PROFILE_RESOURCE_TYPE);
1084        PolicyConstants.PERSONAL_PROFILE_RESOURCE_TYPE
1085                .addPermission(PolicyConstants.PERM_MAINTAIN);
1086
1087        // Password
1088
registerResourceType(PolicyConstants.PASSWORD_RESOURCE_TYPE);
1089            PolicyConstants.PASSWORD_RESOURCE_TYPE
1090                    .addPermission(PolicyConstants.PERM_CHANGE);
1091
1092        // Personal details
1093
registerResourceType(PolicyConstants.PERSONAL_DETAILS_RESOURCE_TYPE);
1094        PolicyConstants.PERSONAL_DETAILS_RESOURCE_TYPE
1095                .addPermission(PolicyConstants.PERM_CHANGE);
1096
1097        // VPN Client
1098
registerResourceType(PolicyConstants.AGENT_RESOURCE_TYPE);
1099        PolicyConstants.AGENT_RESOURCE_TYPE
1100                .addPermission(PolicyConstants.PERM_USE);
1101
1102        // Favorites
1103
registerResourceType(PolicyConstants.FAVORITES_RESOURCE_TYPE);
1104        PolicyConstants.FAVORITES_RESOURCE_TYPE
1105                .addPermission(PolicyConstants.PERM_USE);
1106
1107        // VPN Client
1108
registerResourceType(PolicyConstants.LANGUAGE_RESOURCE_TYPE);
1109        PolicyConstants.LANGUAGE_RESOURCE_TYPE
1110                .addPermission(PolicyConstants.PERM_CHANGE);
1111
1112    }
1113
1114    /*
1115     * (non-Javadoc)
1116     *
1117     * @see com.sslexplorer.policyframework.PolicyDatabase#getGrantedResourcesOfType(com.sslexplorer.permissions.Principal,
1118     * com.sslexplorer.boot.policyframework.ResourceType)
1119     */

1120    public List JavaDoc<Integer JavaDoc> getGrantedResourcesOfType(Principal principal, ResourceType type)
1121            throws Exception JavaDoc {
1122        String JavaDoc cacheKey = "grantedResourcesOfType-"
1123                + principal.getPrincipalName() + "-" + principal.getRealm().getResourceId() + "-" + type.getResourceTypeId();
1124        Set JavaDoc<Integer JavaDoc> resourceIds = (Set JavaDoc<Integer JavaDoc>) policyCache.retrieve(cacheKey);
1125
1126        if (resourceIds == null) {
1127            JDBCPreparedStatement ps = null;
1128            resourceIds = new HashSet JavaDoc<Integer JavaDoc>();
1129            try {
1130                ps = db.getStatement("getGrantedResourcesOfType.select");
1131                ps.setInt(1, type.getResourceTypeId());
1132                ps.setString(2, principal.getPrincipalName());
1133                ps.setInt(3, principal instanceof User ? Policy.PRINCIPAL_USER
1134                        : Policy.PRINCIPAL_GROUP);
1135                ps.setInt(4, type.getResourceTypeId());
1136                ps.setInt(5, principal.getRealm().getResourceId());
1137                ResultSet JavaDoc rs = ps.executeQuery();
1138                while (rs.next()) {
1139                    resourceIds.add(new Integer JavaDoc(rs.getInt("resource_id")));
1140                }
1141
1142                if (principal instanceof User) {
1143                    // Now try roles
1144
Role[] r = ((User) principal).getRoles();
1145                    if (r != null) {
1146                        for (int i = 0; i < r.length; i++) {
1147
1148                            if (r[i] == null) {
1149                                log.warn("NULL role in principal "
1150                                        + principal.getPrincipalName());
1151                                continue;
1152                            }
1153
1154                            ps.reset();
1155                            ps = db
1156                                    .getStatement("getGrantedResourcesOfType.select");
1157                            ps.setInt(1, type.getResourceTypeId());
1158                            ps.setString(2, r[i].getPrincipalName());
1159                            ps.setInt(3, Policy.PRINCIPAL_GROUP);
1160                            ps.setInt(4, type.getResourceTypeId());
1161                            ps.setInt(5, principal.getRealm().getResourceId());
1162                            try {
1163                                rs = ps.executeQuery();
1164                                while (rs.next()) {
1165                                    resourceIds.add(new Integer JavaDoc(rs
1166                                            .getInt("resource_id")));
1167                                }
1168                            } finally {
1169                                ps.releasePreparedStatement();
1170                            }
1171                        }
1172                    }
1173                }
1174            } finally {
1175                if (ps != null) {
1176                    ps.releasePreparedStatement();
1177                }
1178            }
1179            storeToCache(cacheKey, (Serializable JavaDoc) resourceIds);
1180        }
1181        return new ArrayList JavaDoc<Integer JavaDoc>(resourceIds);
1182    }
1183
1184    /*
1185     * (non-Javadoc)
1186     *
1187     * @see com.sslexplorer.policyframework.PolicyDatabase#isPrincipalGrantedResourcesOfType(com.sslexplorer.permissions.Principal,
1188     * com.sslexplorer.boot.policyframework.ResourceType, java.util.List)
1189     */

1190    public boolean isPrincipalGrantedResourcesOfType(Principal principal,
1191            ResourceType resourceRequired, List JavaDoc resourceTypesToExclude)
1192            throws Exception JavaDoc {
1193
1194        String JavaDoc cacheKey = "isGrantedResourceOfType-"
1195                + principal.getPrincipalName()
1196                + "-"
1197                + (resourceRequired == null ? "" : String
1198                        .valueOf(resourceRequired.getResourceTypeId()));
1199        Boolean JavaDoc val = (Boolean JavaDoc) policyCache.retrieve(cacheKey);
1200        if (val == null) {
1201            JDBCPreparedStatement ps = null;
1202            if (resourceRequired == null) {
1203                // Is the user granted ANY resources of ANY type
1204
ps = db.getStatement("isPrincipalGranted.selectAny");
1205                ps.setString(1, principal.getPrincipalName());
1206                ps.setInt(2, principal instanceof User ? Policy.PRINCIPAL_USER
1207                                : Policy.PRINCIPAL_GROUP);
1208                ps.setInt(3, principal.getRealm().getResourceId());
1209            } else {
1210                // Is the user granted ANY resources of a particular type
1211
ps = db.getStatement("isPrincipalGranted.selectType");
1212                ps.setInt(1, resourceRequired.getResourceTypeId());
1213                ps.setString(2, principal.getPrincipalName());
1214                ps.setInt(3, principal instanceof User ? Policy.PRINCIPAL_USER
1215                        : Policy.PRINCIPAL_GROUP);
1216                ps.setInt(4, resourceRequired.getResourceTypeId());
1217                ps.setInt(5, principal.getRealm().getResourceId());
1218            }
1219            try {
1220                ResultSet JavaDoc rs = ps.executeQuery();
1221
1222                // First check the if provided principal has access
1223

1224                while (true) {
1225                    if (rs.next()) {
1226                        if (resourceTypesToExclude == null
1227                                || resourceTypesToExclude.size() == 0) {
1228                            val = Boolean.TRUE;
1229                            break;
1230                        }
1231                        int rtn = rs.getInt("resource_type");
1232                        ResourceType rt = getResourceType(rtn);
1233                        if (rt == null) {
1234                            log
1235                                    .warn("Failed to locate resource type with ID of "
1236                                            + rtn
1237                                            + ". Its possible this was created by a plugin which is no longer available.");
1238                        } else {
1239                            if (!resourceTypesToExclude.contains(rt)) {
1240                                val = Boolean.TRUE;
1241                                break;
1242                            }
1243                        }
1244                    } else {
1245                        break;
1246                    }
1247                }
1248
1249                // If the principal is a user, the get their roles and check
1250
// those as well
1251
if (val == null && principal instanceof User) {
1252                    // Now try roles
1253
Role[] r = ((User) principal).getRoles();
1254                    if (r != null) {
1255                        for (int i = 0; val == null && i < r.length; i++) {
1256
1257                            if (r[i] == null) {
1258                                log.warn("NULL role in principal "
1259                                        + principal.getPrincipalName());
1260                                continue;
1261                            }
1262
1263                            ps.reset();
1264                            if (resourceRequired == null) {
1265                                ps = db
1266                                        .getStatement("isPrincipalGranted.selectAny");
1267                                ps.setString(1, r[i].getPrincipalName());
1268                                ps.setInt(2, Policy.PRINCIPAL_GROUP);
1269                                ps.setInt(3, principal.getRealm().getResourceId());
1270                            } else {
1271                                ps = db
1272                                        .getStatement("isPrincipalGranted.selectType");
1273                                ps.setInt(1, resourceRequired
1274                                        .getResourceTypeId());
1275                                ps.setString(2, r[i].getPrincipalName());
1276                                ps.setInt(3, Policy.PRINCIPAL_GROUP);
1277                                ps.setInt(4, resourceRequired
1278                                        .getResourceTypeId());
1279                                ps.setInt(5, principal.getRealm().getResourceId());
1280                            }
1281
1282                            try {
1283                                rs = ps.executeQuery();
1284                                while (true) {
1285                                    if (rs.next()) {
1286                                        if (resourceTypesToExclude == null
1287                                                || resourceTypesToExclude
1288                                                        .size() == 0) {
1289                                            val = Boolean.TRUE;
1290                                            break;
1291                                        }
1292                                        int rtn = rs.getInt("resource_type");
1293                                        ResourceType rt = getResourceType(rtn);
1294                                        if (rt == null) {
1295                                            log
1296                                                    .warn("Failed to locate resource type with ID of "
1297                                                            + rtn
1298                                                            + ". Its possible this was created by a plugin which is no longer available.");
1299                                        } else {
1300                                            if (!resourceTypesToExclude
1301                                                    .contains(rt)) {
1302                                                val = Boolean.TRUE;
1303                                                break;
1304                                            }
1305                                        }
1306                                    } else {
1307                                        break;
1308                                    }
1309                                }
1310                            } finally {
1311                                ps.releasePreparedStatement();
1312                            }
1313                        }
1314                    }
1315                }
1316
1317            } finally {
1318                ps.releasePreparedStatement();
1319            }
1320            if (val == null) {
1321                val = Boolean.FALSE;
1322            }
1323            
1324            storeToCache(cacheKey, val);
1325        }
1326        return val.booleanValue();
1327    }
1328
1329    /* (non-Javadoc)
1330     * @see com.sslexplorer.policyframework.PolicyDatabase#getPoliciesOfDelegatedAccessRights(com.sslexplorer.policyframework.ResourceType, java.lang.String, com.sslexplorer.security.User, boolean)
1331     */

1332    public List JavaDoc<Policy> getPoliciesOfDelegatedAccessRights(
1333            ResourceType resourceType, String JavaDoc permissionClass, User user) throws Exception JavaDoc {
1334        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(
1335                "policiesOfDelegatedResourcePermissions");
1336        if (resourceType != null) {
1337            buf.append("-");
1338            buf.append(resourceType.getResourceTypeId());
1339        }
1340        if (permissionClass != null) {
1341            buf.append("-");
1342            buf.append(permissionClass);
1343        }
1344        buf.append("-");
1345        buf.append(user.getPrincipalName());
1346        String JavaDoc cacheKey = buf.toString();
1347        List JavaDoc<Policy> l = (List JavaDoc<Policy>) policyCache.retrieve(cacheKey);
1348        if (l == null) {
1349            l = new ArrayList JavaDoc<Policy>();
1350            List JavaDoc resourcePermissions = getAccessRights();
1351            AccessRights resourcePermission = null;
1352            AccessRight accessRight = null;
1353            for (Iterator JavaDoc i = resourcePermissions.iterator(); i.hasNext();) {
1354                resourcePermission = (AccessRights) i.next();
1355                if (isPrincipalAllowed(user, resourcePermission, true)) {
1356                    if (permissionClass == null
1357                            || permissionClass.equals(resourcePermission
1358                                    .getAccessRightsClass())) {
1359                        for (Iterator JavaDoc j = resourcePermission.getAccessRights()
1360                                .iterator(); j.hasNext();) {
1361
1362                            accessRight = (AccessRight) j
1363                                    .next();
1364                            if (resourceType == null
1365                                    || resourceType
1366                                            .equals(accessRight
1367                                                    .getResourceType())) {
1368                                // LDP - Add the policies attached to a resource
1369
// as well
1370
List JavaDoc del = getPoliciesAttachedToResource(resourcePermission, user.getRealm());
1371
1372                                for (Iterator JavaDoc k = del.iterator(); k.hasNext();) {
1373                                    Policy p = (Policy) k.next();
1374                                    if (!l.contains(p)) {
1375                                        l.add(p);
1376                                    }
1377                                }
1378                                break;
1379                            }
1380                        }
1381                    }
1382
1383                }
1384            }
1385            storeToCache(cacheKey, (Serializable JavaDoc) l);
1386        }
1387        return l;
1388    }
1389
1390    /* (non-Javadoc)
1391     * @see com.sslexplorer.policyframework.PolicyDatabase#getPermittingAccessRights(com.sslexplorer.policyframework.ResourceType, com.sslexplorer.policyframework.Permission, java.lang.String, com.sslexplorer.security.User, boolean, boolean, boolean, com.sslexplorer.realms.Realm)
1392     */

1393    public List JavaDoc<AccessRights> getPermittingAccessRights(ResourceType resourceType,
1394            Permission permission, String JavaDoc permissionClass, User user) throws Exception JavaDoc {
1395        String JavaDoc cacheKey = "permittingResourcePermissions-"
1396                + (resourceType == null ? "" : String.valueOf(resourceType
1397                        .getResourceTypeId()))
1398                + "-"
1399                + (permission == null ? "" : String.valueOf(permission.getId()))
1400                + "-" + (permissionClass == null ? "" : permissionClass) + "-"
1401                + user.getPrincipalName();
1402        List JavaDoc<AccessRights> l = (List JavaDoc<AccessRights>) policyCache.retrieve(cacheKey);
1403        if (l == null) {
1404            l = new ArrayList JavaDoc<AccessRights>();
1405            List JavaDoc resourcePermissions = getAccessRights();
1406            AccessRights resourcePermission = null;
1407            AccessRight accessRight = null;
1408
1409            /*
1410             * First iterate through all of the resource permissions looking for
1411             * what is visible at the top level.
1412             */

1413
1414            for (Iterator JavaDoc i = resourcePermissions.iterator(); i.hasNext();) {
1415                resourcePermission = (AccessRights) i.next();
1416                if (permissionClass == null
1417                        || permissionClass.equals(resourcePermission
1418                                .getAccessRightsClass())) {
1419                    // Check the user is allowed
1420
if (isPrincipalAllowed(
1421                                user, resourcePermission, true)) {
1422                        // Iterator through all permissions in the resource
1423
for (Iterator JavaDoc j = resourcePermission
1424                                .getAccessRights().iterator(); j.hasNext();) {
1425                            accessRight = (AccessRight) j
1426                                    .next();
1427                            // Until the resource type matches
1428
if (resourceType == null
1429                                    || resourceType
1430                                            .equals(accessRight
1431                                                    .getResourceType())) {
1432                                // Until at least one permission matches
1433
if (permission == null
1434                                        || permission.getId() == accessRight
1435                                                .getPermission()
1436                                                .getId()) {
1437                                    l.add(resourcePermission);
1438                                    break;
1439                                }
1440                            }
1441                        }
1442                    }
1443                }
1444            }
1445
1446            // Sort and cache
1447
Collections.sort(resourcePermissions);
1448            storeToCache(cacheKey, (Serializable JavaDoc) l);
1449        }
1450        return l;
1451    }
1452
1453    /*
1454     * (non-Javadoc)
1455     *
1456     * @see com.sslexplorer.policyframework.PolicyDatabase#getResourcePermissions(com.sslexplorer.boot.policyframework.ResourceType,
1457     * com.sslexplorer.boot.policyframework.Permission, java.lang.String,
1458     * com.sslexplorer.security.User)
1459     */

1460    public List JavaDoc<AccessRights> getAccessRights(ResourceType resourceType,
1461            Permission permission, String JavaDoc permissionClass, User user)
1462            throws Exception JavaDoc {
1463        StringBuffer JavaDoc buf = new StringBuffer JavaDoc("permission");
1464        if (resourceType != null) {
1465            buf.append("-");
1466            buf.append(resourceType.getResourceTypeId());
1467        }
1468        if (permission != null) {
1469            buf.append("-");
1470            buf.append(permission.getId());
1471        }
1472        if (permissionClass != null) {
1473            buf.append("-");
1474            buf.append(permissionClass);
1475        }
1476        buf.append("-");
1477        buf.append(user.getPrincipalName());
1478        String JavaDoc cacheKey = buf.toString();
1479        List JavaDoc<AccessRights> n = (List JavaDoc<AccessRights>) policyCache.retrieve(cacheKey);
1480        if (n == null) {
1481            ArrayList JavaDoc<AccessRights> l = new ArrayList JavaDoc<AccessRights>();
1482            boolean superUser = LogonControllerFactory.getInstance()
1483                    .isAdministrator(user);
1484            List JavaDoc allAccessRights = getAccessRights();
1485            AccessRights accessRights = null;
1486            AccessRight accessRight = null;
1487
1488            /*
1489             * First iterate through all of the resource permissions looking for
1490             * what is visible at the top level.
1491             */

1492
1493            for (Iterator JavaDoc i = allAccessRights.iterator(); i.hasNext();) {
1494                accessRights = (AccessRights) i.next();
1495                if (permissionClass == null || permissionClass.equals(accessRights.getAccessRightsClass())) {
1496                    // Check the user is allowed
1497
if (isPrincipalAllowed(user, accessRights, true)) {
1498
1499                        // Iterator through all permissions in the resource
1500
for (Iterator JavaDoc j = accessRights.getAccessRights().iterator(); j.hasNext();) {
1501                            accessRight = (AccessRight) j.next();
1502                            // Until the resource type matches
1503
if (resourceType == null || resourceType.equals(accessRight.getResourceType())) {
1504                                // Until at least one permission matches
1505
if (permission == null || permission.getId() == accessRight.getPermission().getId()) {
1506                                    l.add(accessRights);
1507                                    break;
1508                                }
1509                            }
1510                        }
1511                    }
1512                }
1513            }
1514
1515            /*
1516             * Now iterate again, also adding resource permissions that have one
1517             * of the top level resources permissions as parent.
1518             */

1519            if (!superUser) { // Super user should already have all resource
1520
// permissions anyway() + ")");
1521
n = new ArrayList JavaDoc<AccessRights>();
1522                for (Iterator JavaDoc i = allAccessRights.iterator(); i.hasNext();) {
1523                    accessRights = (AccessRights) i.next();
1524                    if (!l.contains(accessRights)) {
1525                        n.add(accessRights);
1526                    }
1527                }
1528            } else {
1529                n = l;
1530            }
1531
1532            // Sort and cache
1533
Collections.sort(n);
1534            storeToCache(cacheKey, (Serializable JavaDoc) n);
1535        }
1536        return n;
1537    }
1538
1539    void deleteResourcePermissionRelationships(JDBCPreparedStatement ps, int id)
1540            throws Exception JavaDoc {
1541        try {
1542            ps = db
1543                    .getStatement("deleteResourcePermissionRelationships.delete");
1544            ps.setInt(1, id);
1545            ps.execute();
1546        } finally {
1547            ps.releasePreparedStatement();
1548        }
1549    }
1550
1551    boolean checkPolicy(Policy policy, Resource resource, Principal principal)
1552            throws Exception JavaDoc {
1553        List JavaDoc principals = getPrincipalsGrantedPolicy(policy, principal.getRealm());
1554        for (Iterator JavaDoc i = principals.iterator(); i.hasNext();) {
1555            Principal p = (Principal) i.next();
1556            if (p.equals(principal)) {
1557                return true;
1558            }
1559        }
1560        return false;
1561    }
1562
1563    void storeToCache(String JavaDoc key, Serializable JavaDoc object) {
1564        if (log.isDebugEnabled()) {
1565            log.debug("Caching under " + key + ", ttl=" + CACHE_TTL + ", cost="
1566                    + CACHE_COST);
1567        }
1568
1569        // NOTE Temporary code to make sure policy objects are serializable, in development and testing
1570
if ("true".equals(System.getProperty("sslexplorer.useDevConfig")) | "true".equals(System.getProperty("sslexplorer.testing"))) {
1571            ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
1572            try {
1573                ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(baos);
1574                oos.writeObject(object);
1575            } catch (Exception JavaDoc e) {
1576                String JavaDoc string = "********** Failed to cache policy database object. There is probably a non-serializable object somewhere in the object graph. PLEASE FIX ME ****************";
1577                System.err
1578                        .println(string);
1579                e.printStackTrace();
1580                throw new RuntimeException JavaDoc(string);
1581            }
1582        }
1583
1584        policyCache.store(key, object, new Long JavaDoc(CACHE_TTL.longValue()
1585                + System.currentTimeMillis()), CACHE_COST);
1586        if (log.isDebugEnabled()) {
1587            log.debug("NUM_RETRIEVE_REQUESTED "
1588                    + policyCache.getStat(CacheStat.NUM_RETRIEVE_REQUESTED));
1589            log.debug("NUM_RETRIEVE_FOUND "
1590                    + policyCache.getStat(CacheStat.NUM_RETRIEVE_FOUND));
1591            log.debug("NUM_RETRIEVE_NOT_FOUND "
1592                    + policyCache.getStat(CacheStat.NUM_RETRIEVE_NOT_FOUND));
1593            log.debug("NUM_STORE_REQUESTED "
1594                    + policyCache.getStat(CacheStat.NUM_STORE_REQUESTED));
1595            log.debug("NUM_STORE_STORED "
1596                    + policyCache.getStat(CacheStat.NUM_STORE_STORED));
1597            log.debug("NUM_STORE_NOT_STORED "
1598                    + policyCache.getStat(CacheStat.NUM_STORE_NOT_STORED));
1599            log.debug("CUR_CAPACITY "
1600                    + policyCache.getStat(CacheStat.CUR_CAPACITY));
1601        }
1602    }
1603
1604    Policy buildPolicy(ResultSet JavaDoc rs) throws Exception JavaDoc {
1605        Timestamp JavaDoc cd = rs.getTimestamp("date_created");
1606        Calendar JavaDoc c = Calendar.getInstance();
1607        c.setTimeInMillis(cd == null ? System.currentTimeMillis() : cd
1608                .getTime());
1609        Timestamp JavaDoc ad = rs.getTimestamp("date_amended");
1610        Calendar JavaDoc a = Calendar.getInstance();
1611        a.setTimeInMillis(ad == null ? System.currentTimeMillis() : ad
1612                .getTime());
1613        return new DefaultPolicy(rs.getInt("id"), rs.getString("policy_name"),
1614                rs.getString("policy_description"),
1615                rs.getInt("policy_type_id"), c, a, rs.getInt("realm_id"));
1616    }
1617
1618    List JavaDoc<AccessRights> buildResourcePermission(ResultSet JavaDoc rs) throws Exception JavaDoc {
1619        List JavaDoc<AccessRight> perms = null;
1620        AccessRights r = null;
1621        List JavaDoc<AccessRights> l = new ArrayList JavaDoc<AccessRights>();
1622        int lastId = -1;
1623        while (rs.next()) {
1624            int id = rs.getInt("resource_id");
1625            int realmID = rs.getInt("realm_id");
1626            if (id != lastId) {
1627                perms = new ArrayList JavaDoc<AccessRight>();
1628                Timestamp JavaDoc cd = rs.getTimestamp("date_created");
1629                Calendar JavaDoc c = Calendar.getInstance();
1630                c.setTimeInMillis(cd == null ? System.currentTimeMillis() : cd
1631                        .getTime());
1632                Timestamp JavaDoc ad = rs.getTimestamp("date_amended");
1633                Calendar JavaDoc a = Calendar.getInstance();
1634                a.setTimeInMillis(ad == null ? System.currentTimeMillis() : ad
1635                        .getTime());
1636                r = new DefaultAccessRights(realmID, id, rs
1637                        .getString("resource_name"), rs
1638                        .getString("resource_description"), perms, rs
1639                        .getString("resource_class"), c, a);
1640                l.add(r);
1641                lastId = id;
1642            }
1643            int resourceTypeId = rs.getInt("resource_type_id");
1644            ResourceType t = getResourceType(resourceTypeId);
1645            if (t == null) {
1646                log.warn("No resource type with Id of " + resourceTypeId
1647                        + " for resource permission " + id + ", ignoring");
1648
1649            } else {
1650                int permId = rs.getInt("permission_id");
1651                Permission drp = t.getPermission(permId);
1652                if (drp == null) {
1653                    log.warn("No permission with Id of " + permId
1654                            + " for resource type " + resourceTypeId
1655                            + " and resource permission " + id + ", ignoring");
1656                } else {
1657                    AccessRight p = new AccessRight(
1658                            t, drp);
1659                    perms.add(p);
1660                }
1661            }
1662        }
1663        return l;
1664    }
1665
1666    void updateResourcePermissionRelationships(JDBCPreparedStatement ps,
1667            AccessRights dr) throws Exception JavaDoc {
1668        deleteResourcePermissionRelationships(ps, dr.getResourceId());
1669        for (Iterator JavaDoc i = dr.getAccessRights().iterator(); i.hasNext();) {
1670            AccessRight perm = (AccessRight) i
1671                    .next();
1672            JDBCPreparedStatement ps2 = db
1673                    .getStatement("updateResourcePermission.insertPermissions");
1674            try {
1675                ps2.setInt(1, dr.getResourceId());
1676                ps2.setInt(2, perm.getResourceType().getResourceTypeId());
1677                ps2.setInt(3, perm.getPermission().getId());
1678                ps2.execute();
1679            } finally {
1680                ps2.releasePreparedStatement();
1681            }
1682        }
1683    }
1684
1685    public int getEveryonePolicyIDForRealm(Realm realm) throws Exception JavaDoc {
1686        int id = 0;
1687        JDBCPreparedStatement ps = db.getStatement("select.everyone.policy.id");
1688        ps.setString(1, PolicyConstants.EVERYONE_POLICY_NAME);
1689        ps.setInt(2, realm.getResourceId());
1690        try {
1691            ResultSet JavaDoc rs = ps.executeQuery();
1692            if (rs.next()) {
1693                id = rs.getInt("ID");
1694            }
1695        } finally {
1696            ps.releasePreparedStatement();
1697        }
1698        return id;
1699    }
1700
1701    /* (non-Javadoc)
1702     * @see com.sslexplorer.policyframework.PolicyDatabase#isResourceInRealm(com.sslexplorer.policyframework.Resource, com.sslexplorer.realms.Realm)
1703     */

1704    public boolean isResourceInRealm(Resource resource, Realm realm) throws Exception JavaDoc {
1705        JDBCPreparedStatement ps = db.getStatement("is.resource.in.realm");
1706        ps.setInt(1, resource.getResourceId());
1707        ps.setInt(2, resource.getResourceType().getResourceTypeId());
1708        ps.setInt(3, realm.getResourceId());
1709        try {
1710            ResultSet JavaDoc rs = ps.executeQuery();
1711            if (rs.next()) {
1712                return true;
1713            }
1714        } finally {
1715            ps.releasePreparedStatement();
1716        }
1717        return false;
1718    }
1719    
1720    /* (non-Javadoc)
1721     * @see com.sslexplorer.policyframework.PolicyDatabase#getGrantingPolicyForUser(com.sslexplorer.security.User, com.sslexplorer.policyframework.Resource)
1722     */

1723    public Policy getGrantingPolicyForUser(User user, Resource resource) throws Exception JavaDoc {
1724        Policy policy = null;
1725        if((policy = getGrantingPolicy(user, resource))==null) {
1726            Role[] roles = user.getRoles();
1727            for(int i=0;i<roles.length;i++) {
1728                
1729                if((policy = getGrantingPolicy(roles[i], resource))!=null) {
1730                    break;
1731                }
1732            }
1733        }
1734        return policy;
1735            
1736    }
1737
1738    /**
1739     * Get the policy thats grants the specified principal access to the
1740     * specified resource.
1741     *
1742     * @param principal principal
1743     * @param resource resource
1744     * @return policy that grants access or <code>null</code> if no policy grants access
1745     * @throws Exception on any error
1746     */

1747    private Policy getGrantingPolicy(Principal principal, Resource resource) throws Exception JavaDoc {
1748        String JavaDoc cacheKey = "grantingPolicy-" + principal.getPrincipalName() + "-realmID-" + principal.getRealm().getResourceId()
1749                + "-" + resource.getResourceId() + "-"
1750                + resource.getResourceType().getResourceTypeId();
1751        Policy val = (Policy) policyCache.retrieve(cacheKey);
1752        if (val == null) {
1753            List JavaDoc policies = getPoliciesAttachedToResource(resource, principal.getRealm());
1754            for (Iterator JavaDoc i = policies.iterator(); val == null && i.hasNext();) {
1755                Policy p = (Policy) i.next();
1756                if (isPolicyGrantedToPrincipal(p, principal)) {
1757                    val = p;
1758                }
1759                if (principal instanceof User) {
1760                    Role[] r = ((User) principal).getRoles();
1761                    if (r != null) {
1762                        for (int j = 0; val == null && j < r.length; j++) {
1763                            if (r[j]!=null && isPolicyGrantedToPrincipal(p, r[j])) {
1764                                val = p;
1765                            }
1766                        }
1767                    }
1768                }
1769            }
1770            storeToCache(cacheKey, val);
1771        }
1772        return val;
1773        
1774    }
1775
1776    /* (non-Javadoc)
1777     * @see com.sslexplorer.policyframework.PolicyDatabase#isPolicyGrantedToUser(com.sslexplorer.policyframework.Policy, com.sslexplorer.security.User)
1778     */

1779    public boolean isPolicyGrantedToUser(Policy policy, User user) throws Exception JavaDoc {
1780        boolean found = false;
1781        if(!isPolicyGrantedToPrincipal(policy, user)) {
1782            Role[] roles = user.getRoles();
1783            for(int i=0;i<roles.length;i++) {
1784                if(isPolicyGrantedToPrincipal(policy, roles[i])) {
1785                    found = true;
1786                    break;
1787                }
1788            }
1789        } else
1790            found = true;
1791        return found;
1792    }
1793
1794    /* (non-Javadoc)
1795     * @see com.sslexplorer.policyframework.PolicyDatabase#detachResourceFromPolicyList(com.sslexplorer.policyframework.Resource, com.sslexplorer.security.SessionInfo)
1796     */

1797    public void detachResourceFromPolicyList(Resource resource, SessionInfo session) throws Exception JavaDoc {
1798        List JavaDoc policies = getPolicies(session.getUser().getRealm());
1799        for (Iterator JavaDoc i = policies.iterator(); i.hasNext();) {
1800            Policy p = (Policy) i.next();
1801            if(isResourceAttachedToPolicy(resource, p, session.getUser().getRealm())) {
1802                if (log.isDebugEnabled())
1803                    log.debug("Detaching policy " + p.getResourceName() + " (" + p.getResourceId() + ") to resource "
1804                                + resource.getResourceName() + "(id=" + resource.getResourceId() + ", type="
1805                                + resource.getResourceType() + ")");
1806                try {
1807                    detachResourceFromPolicy(resource, p, session.getUser().getRealm());
1808                    CoreServlet.getServlet().fireCoreEvent(new ResourceDetachedFromPolicyEvent(this, resource, p, session, CoreEvent.STATE_SUCCESSFUL));
1809                }
1810                catch(Exception JavaDoc e) {
1811                    CoreServlet.getServlet().fireCoreEvent(new ResourceDetachedFromPolicyEvent(this, resource, p, session, CoreEvent.STATE_UNSUCCESSFUL));
1812                }
1813            }
1814        }
1815    }
1816
1817    /* (non-Javadoc)
1818     * @see com.sslexplorer.policyframework.PolicyDatabase#attachResourceToPolicyList(com.sslexplorer.policyframework.Resource, com.sslexplorer.boot.PropertyList, com.sslexplorer.security.SessionInfo)
1819     */

1820    public void attachResourceToPolicyList(Resource resource, PropertyList selectedPolicies, SessionInfo session) throws Exception JavaDoc {
1821        List JavaDoc l = getPoliciesAttachedToResource(resource, session.getUser().getRealm());
1822        for (Iterator JavaDoc i = l.iterator(); i.hasNext();) {
1823            Policy p = (Policy) i.next();
1824            if(!selectedPolicies.contains(String.valueOf(p.getResourceId()))) {
1825                if (log.isDebugEnabled())
1826                    log.debug("Detaching policy " + p.getResourceName() + " (" + p.getResourceId() + ") to resource "
1827                                + resource.getResourceName() + "(id=" + resource.getResourceId() + ", type="
1828                                + resource.getResourceType() + ")");
1829                try {
1830                    detachResourceFromPolicy(resource, p, session.getUser().getRealm());
1831                    CoreServlet.getServlet().fireCoreEvent(new ResourceDetachedFromPolicyEvent(this, resource, p, session, CoreEvent.STATE_SUCCESSFUL));
1832                }
1833                catch(Exception JavaDoc e) {
1834                    CoreServlet.getServlet().fireCoreEvent(new ResourceDetachedFromPolicyEvent(this, resource, p, session, CoreEvent.STATE_UNSUCCESSFUL));
1835                    throw e;
1836                }
1837            }
1838        }
1839        int idx = 0;
1840        for (Iterator JavaDoc i = selectedPolicies.iterator(); i.hasNext(); ) {
1841            String JavaDoc pn = (String JavaDoc)i.next();
1842            Policy p = getPolicy(Integer.parseInt(pn));
1843            if (!l.contains(p)) {
1844                if (log.isDebugEnabled())
1845                    log.debug("Attaching policy " + p.getResourceName() + " (" + p.getResourceId() + ") to resource "
1846                                + resource.getResourceName() + "(id=" + resource.getResourceId() + ", type="
1847                                + resource.getResourceType() + ")");
1848                try {
1849                    attachResourceToPolicy(resource, p, idx++, session.getUser().getRealm());
1850                    CoreServlet.getServlet().fireCoreEvent(new ResourceAttachedToPolicyEvent(this, resource, p, session, CoreEvent.STATE_SUCCESSFUL));
1851                }
1852                catch(Exception JavaDoc e) {
1853                    CoreServlet.getServlet().fireCoreEvent(new ResourceAttachedToPolicyEvent(this, resource, p, session, CoreEvent.STATE_UNSUCCESSFUL));
1854                    throw e;
1855                }
1856            }
1857        }
1858    }
1859
1860    public List JavaDoc<AccessRights> getAccessRights(int realmID) throws Exception JavaDoc {
1861        String JavaDoc cacheKey = "resourcePermissions-realmID=" + realmID;
1862        List JavaDoc<AccessRights> val = (List JavaDoc<AccessRights>) policyCache.retrieve(cacheKey);
1863        if (val == null) {
1864            JDBCPreparedStatement ps = db
1865                    .getStatement("getResourcePermissions.realm.select");
1866            try {
1867                ps.setInt(1, realmID);
1868                ResultSet JavaDoc rs = ps.executeQuery();
1869                val = buildResourcePermission(rs);
1870            } finally {
1871                ps.releasePreparedStatement();
1872            }
1873        }
1874        
1875        return val;
1876    }
1877
1878}
Popular Tags