KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jguard > ext > authorization > manager > JdbcAuthorizationManager


1 /*
2 jGuard is a security framework based on top of jaas (java authentication and authorization security).
3 it is written for web applications, to resolve simply, access control problems.
4 version $Name$
5 http://sourceforge.net/projects/jguard/
6
7 Copyright (C) 2004 Charles GAY
8
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
13
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
23
24 jGuard project home page:
25 http://sourceforge.net/projects/jguard/
26
27 */

28 package net.sf.jguard.ext.authorization.manager;
29
30 import java.io.File JavaDoc;
31 import java.io.FileInputStream JavaDoc;
32 import java.io.FileNotFoundException JavaDoc;
33 import java.io.IOException JavaDoc;
34 import java.net.URI JavaDoc;
35 import java.net.URISyntaxException JavaDoc;
36 import java.security.Permission JavaDoc;
37 import java.security.Principal JavaDoc;
38 import java.sql.Connection JavaDoc;
39 import java.sql.PreparedStatement JavaDoc;
40 import java.sql.ResultSet JavaDoc;
41 import java.sql.SQLException JavaDoc;
42 import java.util.ArrayList JavaDoc;
43 import java.util.Arrays JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.HashSet JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Properties JavaDoc;
50 import java.util.Set JavaDoc;
51 import java.util.Stack JavaDoc;
52 import java.util.logging.Level JavaDoc;
53 import java.util.logging.Logger JavaDoc;
54
55 import net.sf.jguard.core.CoreConstants;
56 import net.sf.jguard.core.authorization.permissions.Domain;
57 import net.sf.jguard.core.authorization.permissions.JGPermissionCollection;
58 import net.sf.jguard.core.authorization.permissions.JGPositivePermissionCollection;
59 import net.sf.jguard.core.authorization.permissions.NoSuchPermissionException;
60 import net.sf.jguard.core.authorization.permissions.PermissionUtils;
61 import net.sf.jguard.core.principals.RolePrincipal;
62 import net.sf.jguard.core.util.FileUtils;
63 import net.sf.jguard.ext.SecurityConstants;
64 import net.sf.jguard.ext.authorization.AuthorizationException;
65 import net.sf.jguard.ext.database.ConnectionFactory;
66 import net.sf.jguard.ext.database.DatabaseUtils;
67 import net.sf.jguard.ext.util.XMLUtils;
68
69 /**
70  * jdbc-based AuthorizationManager class used for all database backend.
71  * @author <a HREF="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
72  * @author <a HREF="mailto:vinipitta@users.sourceforge.net">Vinicius Pitta Lima de Araujo</a>
73  * @author <a HREF="mailto:tandilero@users.sourceforge.net">Maximiliano Batelli</a>
74  */

75 public class JdbcAuthorizationManager extends AbstractAuthorizationManager implements AuthorizationManager{
76
77     private static final Logger JavaDoc logger = Logger.getLogger(JdbcAuthorizationManager.class.getName());
78
79
80     protected static final String JavaDoc NAME = "name";
81     protected static final String JavaDoc DOMAIN_NAME= "domain_name";
82
83     //domainIds is only dedicated to the jdbc subclasses
84
protected Map JavaDoc domainIds;
85
86     //table and index names
87
protected static String JavaDoc jgDomainSeq ="jg_domain_seq";
88     protected static String JavaDoc jgPermissionSeq ="jg_permission_seq";
89     protected static String JavaDoc jgAppPrincipalSeq ="jg_app_principal_seq";
90     protected static String JavaDoc jgUrlQuerySeq ="jg_url_query_seq";
91     protected static String JavaDoc jgPrincipalDomain ="jg_principal_domain";
92     protected static String JavaDoc jgDomain ="jg_domain";
93     protected static String JavaDoc jgAppPrincipal ="jg_app_principal";
94     protected static String JavaDoc jgPrincipalPermission ="jg_principal_permission";
95     protected static String JavaDoc jgPermission= "jg_permission";
96     protected static String JavaDoc jgUrlQuery = "jg_urlquery";
97     protected static String JavaDoc jgPrincipalHierarchy = "jg_principal_principal";
98
99     //SQL queries
100
protected String JavaDoc PRINCIPALS_HIERARCHY = "PRINCIPALS_HIERARCHY";
101     protected String JavaDoc CREATE_PRINCIPAL_INHERITANCE = "CREATE_PRINCIPAL_INHERITANCE";
102     protected String JavaDoc DELETE_PRINCIPAL_INHERITANCE = "DELETE_PRINCIPAL_INHERITANCE";
103
104
105     protected String JavaDoc PRINCIPALS="PRINCIPALS";
106     protected String JavaDoc PERMISSIONS_FROM_PRINCIPAL="PERMISSIONS_FROM_PRINCIPAL";
107     protected String JavaDoc PERMISSIONS_FROM_DOMAINS="PERMISSIONS_FROM_DOMAINS";
108     protected String JavaDoc PERMISSIONS="PERMISSIONS";
109     protected String JavaDoc CREATE_PERMISSION="CREATE_PERMISSION";
110     protected String JavaDoc CREATE_DOMAIN="CREATE_DOMAIN";
111     protected String JavaDoc CREATE_PRINCIPAL_PERMISSION="CREATE_PRINCIPAL_PERMISSION";
112     protected String JavaDoc CREATE_PRINCIPAL_DOMAIN="CREATE_PRINCIPAL_DOMAIN";
113     protected String JavaDoc DOMAINS="DOMAINS";
114     //delete a domain
115
protected String JavaDoc DELETE_DOMAIN="DELETE_DOMAIN";
116     //delete all the association in jg_principal_domain for a specific principal
117
protected String JavaDoc DELETE_PRINCIPAL_DOMAIN="DELETE_PRINCIPAL_DOMAIN";
118     //delete the associations in jg_principal_domain for a specific domain
119
protected String JavaDoc DELETE_DOMAIN_PRINCIPAL="DELETE_DOMAIN_PRINCIPAL";
120
121     protected String JavaDoc UPDATE_DOMAIN="UPDATE_DOMAIN";
122     protected String JavaDoc UPDATE_PERMISSION="UPDATE_PERMISSION";
123     protected String JavaDoc CHANGE_DOMAIN_PERMISSION="CHANGE_DOMAIN_PERMISSION";
124     protected String JavaDoc DELETE_PRINCIPAL="DELETE_PRINCIPAL";
125     protected String JavaDoc CREATE_PRINCIPAL="CREATE_PRINCIPAL";
126     protected String JavaDoc UPDATE_PRINCIPAL="UPDATE_PRINCIPAL";
127     //delete a permission
128
protected String JavaDoc DELETE_PERMISSION="DELETE_PERMISSION";
129     //delete all the association in jg_principal_domain for a specific principal
130
protected String JavaDoc DELETE_PRINCIPAL_PERMISSION="DELETE_PRINCIPAL_PERMISSION";
131     //delete the associations in jg_principal_permission for a specific permission
132
protected String JavaDoc DELETE_PERMISSION_PRINCIPAL="DELETE_PERMISSION_PRINCIPAL";
133     protected String JavaDoc READ_PERMISSION_ID="READ_PERMISSION_ID";
134     protected String JavaDoc READ_DOMAIN_ID ="READ_DOMAIN_ID";
135     protected String JavaDoc READ_PRINCIPAL_ID ="READ_PRINCIPAL_ID";
136
137     private Properties JavaDoc props;
138     private String JavaDoc dbPropertiesLocation;
139     protected ConnectionFactory connectionFactory = null;
140
141     /**
142      * JdbcAuthorizationManager constructor.
143      */

144     public JdbcAuthorizationManager() {
145         super();
146         domainIds = new HashMap JavaDoc();
147     }
148
149     /**
150      * return needed initialization parameters.
151      * @return initialization parameters' list
152      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#getInitParameters()
153      */

154     public List JavaDoc getInitParameters() {
155
156         String JavaDoc[] authorizationParameters = {"authorizationUrl","authorizationLogin",
157                                             "authorizationPassword","authorizationDriver"};
158         return Arrays.asList(authorizationParameters);
159     }
160
161
162     /**
163      * initialize principals.
164      * regroup Principals in a Set.
165      * @return principals Set
166      */

167     private Set JavaDoc initPrincipals() {
168
169         Set JavaDoc ppals = new HashSet JavaDoc();
170         Map JavaDoc principalsMap = new HashMap JavaDoc();
171         PreparedStatement JavaDoc pst;
172         PreparedStatement JavaDoc pst2;
173         PreparedStatement JavaDoc pst3;
174         ResultSet JavaDoc rs;
175         ResultSet JavaDoc rs2;
176         ResultSet JavaDoc rs3;
177        
178         Connection JavaDoc connection = null;
179        try {
180                connection = connectionFactory.getConnection();
181                pst= connection.prepareStatement(props.getProperty(PRINCIPALS));
182                rs = pst.executeQuery();
183
184                while(rs.next()){
185                    RolePrincipal tempJGuardPrincipal = new RolePrincipal();
186                    tempJGuardPrincipal.setName(this.applicationName+"#"+rs.getString(NAME));
187                    String JavaDoc name = rs.getString(NAME);
188
189                    //domains names owned by this principal
190
Set JavaDoc domainNames = new HashSet JavaDoc();
191
192                    //add permissions from principal via domains
193
pst3 = connection.prepareStatement(props.getProperty(PERMISSIONS_FROM_DOMAINS));
194                    pst3.setString(1,name);
195                    rs3 = pst3.executeQuery();
196
197                    //fill principal object with the permissions bound to domains owned by the current principal
198
while(rs3.next()){
199                     String JavaDoc domainName = rs3.getString(DOMAIN_NAME);
200                             if(!domainNames.contains(domainName)){
201                                     domainNames.add(domainName);
202                                 logger.finest(" add domain "+domainName+" to principal "+tempJGuardPrincipal.getLocalName());
203                                     JGPermissionCollection domainTemp = (JGPermissionCollection)domains.get(domainName);
204                                     tempJGuardPrincipal.addDomain(domainTemp);
205                                 }
206
207                         }
208
209                    //add permissions not bound with a domain owned by this principal
210
pst2 = connection.prepareStatement(props.getProperty(PERMISSIONS_FROM_PRINCIPAL));
211                    pst2.setString(1,name);
212                    rs2 = pst2.executeQuery();
213
214                    //fill principal object with their permissions
215
while(rs2.next()){
216                     String JavaDoc permissionName = rs2.getString(NAME);
217                     Permission JavaDoc perm;
218                         try {
219                             perm = (Permission JavaDoc)urlp.getPermission(permissionName);
220                         tempJGuardPrincipal.addPermission(perm);
221                         } catch (NoSuchPermissionException e) {
222                             logger.warning(" permission "+permissionName+" is not present in the JGPermissionCollection ");
223                         }
224                    }
225
226                    ppals.add(tempJGuardPrincipal);
227                    principalsMap.put(tempJGuardPrincipal.getLocalName(), tempJGuardPrincipal);
228                }
229
230
231
232                rs.close();
233                pst.close();
234
235                pst = connection.prepareStatement(props.getProperty(PRINCIPALS_HIERARCHY));
236                rs = pst.executeQuery();
237
238                RolePrincipal ascendantPrincipal = null;
239
240                while (rs.next()) {
241                    String JavaDoc principalAscendantName = rs.getString(1);
242                    String JavaDoc principalDescendantName = rs.getString(2);
243
244                    if (ascendantPrincipal == null || !ascendantPrincipal.getLocalName().equals(principalAscendantName)) {
245                        ascendantPrincipal = (RolePrincipal) principalsMap.get(principalAscendantName);
246                    }
247                    
248                    RolePrincipal descendant = (RolePrincipal)principalsMap.get(principalDescendantName);
249                    ascendantPrincipal.getDescendants().add(descendant);
250
251                    logger.info("Principal " + principalAscendantName + " inherites from principal " + principalDescendantName);
252                }
253
254                rs.close();
255                pst.close();
256
257        } catch (SQLException JavaDoc e) {
258             if (logger.isLoggable(Level.FINEST)) {
259                 logger.finest("initPrincipals in AuthorizationManager SQL ERROR "+ e.getMessage());
260             }
261        }finally{
262            try {
263                connection.close();
264            } catch (SQLException JavaDoc e1) {
265                 logger.log(Level.SEVERE, "listPrincipals()", e1);
266            }
267        }
268
269         return ppals;
270     }
271
272     /**
273      * initialize permissions.
274      * regroup permissions in a JGPermissionCollection.
275      * @return JGPermissionCollection
276      */

277     private JGPermissionCollection initPermissions() {
278
279         JGPermissionCollection urlPc= new JGPositivePermissionCollection();
280         Permission JavaDoc tempPermission = null;
281         String JavaDoc tempPermissionName="";
282         Connection JavaDoc connection2 = null;
283         try {
284                 //get the domains (although the empty domains)
285
connection2 = connectionFactory.getConnection();
286                 PreparedStatement JavaDoc pst2 = connection2.prepareStatement(props.getProperty(DOMAINS));
287                 ResultSet JavaDoc rs2 = pst2.executeQuery();
288                 while(rs2.next()){
289                     String JavaDoc domainName = rs2.getString(NAME);
290                     Long JavaDoc domainId = new Long JavaDoc((rs2.getInt("id")));
291                     JGPermissionCollection domain = new Domain(domainName);
292                     domainsSet.add(domain);
293                     domains.put(domainName,domain);
294                     domainIds.put(domainName,domainId);
295                     Connection JavaDoc connection = null;
296                     try{
297                                 connection = connectionFactory.getConnection();
298                                 PreparedStatement JavaDoc pst = connection.prepareStatement(props.getProperty(PERMISSIONS));
299                                 pst.setLong(1,domainId.longValue());
300                                 ResultSet JavaDoc rs = pst.executeQuery();
301             
302                                //get the corresponding permissions
303
while(rs.next()){
304             
305                                     //new permission
306
if(rs.getString(NAME).equals(tempPermissionName)==false){
307                                         if(tempPermission!=null){
308                                             urlPc.add(tempPermission);
309                                         }
310                                         String JavaDoc clazz = rs.getString(("class"));
311                                         String JavaDoc actions = rs.getString(("actions"));
312                                         try {
313                                             tempPermission = PermissionUtils.getPermission(clazz,rs.getString(NAME),actions);
314                                         } catch (ClassNotFoundException JavaDoc e) {
315                                             logger.warning(e.getMessage());
316                                             continue;
317                                         }
318                                         permissions.put(tempPermission.getName(),tempPermission);
319                                         permissionsSet.add(tempPermission);
320                                         //add the Permission to the domain
321
((JGPermissionCollection)domains.get(domainName)).add(tempPermission);
322             
323                                     }
324                                 }
325             
326                                 //add the last permission
327
if(tempPermission!=null){
328                                     urlPc.add(tempPermission);
329                                 }
330                     }finally{
331                         connection.close();
332                     }
333
334                 }
335
336
337        } catch (SQLException JavaDoc e) {
338
339             if (logger.isLoggable(Level.FINEST)) {
340                 logger.finest("listPermissions() - initializePermissions in AuthorizationManager SQL ERROR "+ e.getMessage());
341             }
342
343        }finally{
344            try {
345             connection2.close();
346         } catch (SQLException JavaDoc e) {
347             throw new RuntimeException JavaDoc(e);
348         }
349        }
350
351         return urlPc;
352     }
353
354     /**
355      * initialize this jdbc permission manager.
356      * @param options a Map which contains informations to configure the AuthorizationManager implementation.
357      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#init(java.util.Properties)
358      */

359     public void init(Map JavaDoc options) {
360         super.init(options);
361         String JavaDoc applicationName= (String JavaDoc)options.get(CoreConstants.APPLICATION_NAME);
362         if(applicationName==null){
363             throw new IllegalArgumentException JavaDoc(" applicationName is null");
364         }
365         this.setApplicationName(applicationName);
366         super.options = options;
367         dbPropertiesLocation = (String JavaDoc)options.get(SecurityConstants.AUTHORIZATION_DATABASE_FILE_LOCATION);
368         dbPropertiesLocation = XMLUtils.resolveLocation(dbPropertiesLocation);
369         props = new Properties JavaDoc();
370         try {
371             File JavaDoc file = FileUtils.getFile(new URI JavaDoc(dbPropertiesLocation));
372             props.load(new FileInputStream JavaDoc(file));
373             logger.finest(" JdbcAuthorizationManager properties = "+props);
374         } catch (FileNotFoundException JavaDoc e2) {
375             logger.severe(" authorization database properties file is not found at this location "+dbPropertiesLocation);
376             e2.printStackTrace();
377         } catch (IOException JavaDoc e2) {
378             logger.severe(" authorization database properties file is not accesible this location "+dbPropertiesLocation+"\n "+e2.getMessage());
379         } catch (URISyntaxException JavaDoc e) {
380             logger.log(Level.SEVERE, " uri of the authorization database properties file hasn't got a valid synthax ",e);
381         }
382
383         //initialize database connection factory
384
connectionFactory = new ConnectionFactory(options);
385         createRequiredDatabaseEntities(props,connectionFactory);
386         boolean empty = isEmpty();
387         if(empty){
388           insertRequiredData();
389         }
390
391         urlp = initPermissions();
392         principalsSet = initPrincipals();
393         Iterator JavaDoc itPrincipalsSet = principalsSet.iterator();
394
395         //populate the corresponding Map to the Set
396
while(itPrincipalsSet.hasNext()){
397             RolePrincipal tempPrincipal = (RolePrincipal)itPrincipalsSet.next();
398             principals.put(tempPrincipal.getLocalName(),tempPrincipal);
399         }
400
401     }
402
403     private static void createRequiredDatabaseEntities(Properties JavaDoc properties,ConnectionFactory connectionFactory) {
404
405         //we create tables
406
List JavaDoc tablesNames = new ArrayList JavaDoc();
407         tablesNames.add("JG_DOMAIN");
408         tablesNames.add("JG_APP_PRINCIPAL");
409         tablesNames.add("JG_PERMISSION");
410         tablesNames.add("JG_PRINCIPAL_PERMISSION");
411         tablesNames.add("JG_PRINCIPAL_DOMAIN");
412         tablesNames.add("JG_PRINCIPAL_HIERARCHY");
413
414         List JavaDoc sequencesNames = new ArrayList JavaDoc();
415         sequencesNames.add("JG_APP_PRINCIPAL_SEQ");
416         sequencesNames.add("JG_PERMISSION_SEQ");
417         sequencesNames.add("JG_DOMAIN_SEQ");
418
419         List JavaDoc foreignkeysNames = new ArrayList JavaDoc();
420         foreignkeysNames.add("FK_PERMISSION_PRINCIPAL");
421         foreignkeysNames.add("FK_PRINCIPAL_PERMISSION");
422         foreignkeysNames.add("FK_DOMAIN_PRINCIPAL");
423         foreignkeysNames.add("FK_PRINCIPAL_DOMAIN");
424         foreignkeysNames.add("FK_PERMISSION_DOMAIN");
425         foreignkeysNames.add("FK_PRINCIPAL_HIERARCHY_PRINCIPAL");
426         foreignkeysNames.add("FK_PRINCIPAL_HIERARCHY_PRINCIPAL2");
427
428         //initialise database
429
DatabaseUtils.createRequiredDatabaseEntities(properties,connectionFactory,sequencesNames,tablesNames,foreignkeysNames);
430
431     }
432
433
434
435     /**
436      * create an URLPermission int the corresponding backend.
437      * @param permission URLPermission
438      * @param domainName the domain the permission belongs to
439      * @throws AuthorizationException
440      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#createPermission(java.security.Permission, java.lang.String)
441      */

442     public void createPermission(Permission JavaDoc permission,String JavaDoc domainName) throws AuthorizationException {
443
444
445         Connection JavaDoc conn = null;
446         PreparedStatement JavaDoc pst = null;
447         //name,uri,description,scheme,domain_id
448
try {
449             conn = connectionFactory.getConnection();
450             pst = conn.prepareStatement(props.getProperty(CREATE_PERMISSION));
451
452             pst.setString(1,permission.getName());
453             pst.setString(2,permission.getActions());
454             pst.setString(3,permission.getClass().getName());
455             Long JavaDoc domainId =(Long JavaDoc)domainIds.get(domainName);
456             pst.setLong(4,domainId.longValue());
457             pst.executeUpdate();
458
459             //add the permission to the permissionCollection
460
urlp.add(permission);
461                 if (logger.isLoggable(Level.FINEST)) {
462                     logger.finest("createPermission() - " + permission
463                             + " added!");
464                     logger.finest("createPermission() - permissions: " + urlp);
465                 }
466             //add the permission to its Domain
467
JGPermissionCollection domain = (JGPermissionCollection)domains.get(domainName);
468             domain.add(permission);
469             permissions.put(permission.getName(),permission);
470             permissionsSet.add(permission);
471
472             /*
473              * udpate the permission list from all principals that have relationship with this
474              * domain. Is this is not done the change will not affect the users principals in this webapp
475              * while the application is not reloaded.
476              */

477             this.updatePrincipals(permission);
478
479
480         } catch (SQLException JavaDoc e) {
481             logger.log(Level.SEVERE, "createPermission(URLPermission, String)", e);
482         }finally{
483             try {
484                 pst.close();
485                 conn.close();
486             } catch (SQLException JavaDoc e1) {
487                 logger.log(Level.SEVERE, "createPermission(URLPermission, String)", e1);
488             }
489         }
490
491
492     }
493
494
495
496     /**
497      * update the URLPermission.
498      * @param oldPermissionName
499      * @param perm
500      * @param newDomainName
501      * @throws AuthorizationException
502      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#updatePermission(java.lang.String, java.security.Permission, java.lang.String)
503      */

504     public void updatePermission(String JavaDoc oldPermissionName, Permission JavaDoc perm, String JavaDoc newDomainName) throws AuthorizationException {
505
506         
507         PreparedStatement JavaDoc pst;
508         Connection JavaDoc conn = null;
509
510             try {
511                 conn = connectionFactory.getConnection();
512                 conn.setAutoCommit(false);
513                 pst = conn.prepareStatement(props.getProperty(UPDATE_PERMISSION));
514
515             // name
516
pst.setString(1,perm.getName());
517             //actions
518
pst.setString(2,perm.getActions());
519             //class
520
pst.setString(3,perm.getClass().getName());
521             //domainId
522
pst.setLong(4,((Long JavaDoc)domainIds.get(newDomainName)).longValue());
523             //old Permission Name
524
pst.setString(5,oldPermissionName);
525             pst.executeUpdate();
526
527             JGPermissionCollection newDomain = (JGPermissionCollection)domains.get(newDomainName);
528
529                 // we are looking for the old domain which contains the updated permission
530
Iterator JavaDoc itDomains = domainsSet.iterator();
531             Permission JavaDoc oldPermission = (Permission JavaDoc) permissions.get(oldPermissionName);
532             while(itDomains.hasNext()){
533                 JGPermissionCollection domain = (JGPermissionCollection)itDomains.next();
534
535                 if(domain.containsPermission(oldPermission)){
536                     domain.removePermission(oldPermission);
537                     //only one domain can contain a permission
538
//so, when we found the 'old' domain which contain the searched permission
539
//we break the loop
540
break;
541                 }
542             }
543
544             //update the "in memory" permission
545
urlp.removePermission(oldPermission);
546             urlp.add(perm);
547             permissions.remove(oldPermissionName);
548             permissions.put(perm.getName(),perm);
549             Iterator JavaDoc itPermissionsSet = permissionsSet.iterator();
550             while(itPermissionsSet.hasNext()){
551                 Permission JavaDoc tempPerm = (Permission JavaDoc)itPermissionsSet.next();
552                 if(tempPerm.getName().equals(oldPermissionName)){
553                     permissionsSet.remove(tempPerm);
554                     break;
555                 }
556             }
557             permissionsSet.add(perm);
558             //add the updated permission to the new domain
559
newDomain.add(perm);
560
561             //update principals
562
this.updatePrincipals(perm);
563                 //we only commit SQL changes if SQL and memory changes are synchronized:
564
//i.e no exception has been raised on the memory scope
565
conn.commit();
566             } catch (SQLException JavaDoc e) {
567                 throw new AuthorizationException(e);
568             }finally{
569                 try {
570                     conn.close();
571                 } catch (SQLException JavaDoc e1) {
572                     logger.log(Level.SEVERE, "updatePermission(String, URLPermission, String)", e1);
573                 }
574             }
575     }
576
577
578
579     /**
580      * delete the permission.
581      * @param permissionName
582      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#deletePermission(java.lang.String)
583      */

584     public void deletePermission(String JavaDoc permissionName) throws AuthorizationException {
585
586        
587         PreparedStatement JavaDoc pst;
588         PreparedStatement JavaDoc pst2;
589         Connection JavaDoc conn = null;
590         try {
591             conn = connectionFactory.getConnection();
592             conn.setAutoCommit(false);
593             //delete associations in jg_principal_permisison
594
//before suppress the corresponding permission
595
pst = conn.prepareStatement(props.getProperty(DELETE_PERMISSION_PRINCIPAL));
596             pst.setString(1,permissionName);
597             logger.finest(props.getProperty(DELETE_PERMISSION_PRINCIPAL));
598             logger.finest("permissionName="+permissionName);
599             pst.executeUpdate();
600             pst.close();
601
602             pst2 = conn.prepareStatement(props.getProperty(DELETE_PERMISSION));
603             pst2.setString(1,permissionName);
604             pst2.executeUpdate();
605
606             this.removePermissionFromPrincipals(permissionName);
607             Permission JavaDoc permission = null;
608             try {
609                 permission = (Permission JavaDoc)urlp.getPermission(permissionName);
610             } catch (NoSuchPermissionException e) {
611                 throw new AuthorizationException(e);
612             }
613             Domain domain = getDomain(permission);
614             domain.removePermission(permission);
615             permissions.remove(permission.getName());
616             permissionsSet.remove(permission);
617             urlp.removePermission(permission);
618             //update the principals that have this permission by the domain that own this permission
619
this.updatePrincipals(domain);
620
621             Iterator JavaDoc urlpIt = urlp.getPermissions().iterator();
622             while(urlpIt.hasNext()){
623                 Permission JavaDoc tempPermission = (Permission JavaDoc)urlpIt.next();
624                 if(tempPermission.getName().equals(permissionName)){
625                     //remove the permission in the Set
626
getDomain(tempPermission).removePermission(tempPermission);
627                     //remove the permission in the permissionCollection
628
urlpIt.remove();
629                     break;
630                 }
631
632             }
633             conn.commit();
634         } catch (SQLException JavaDoc e) {
635             logger.log(Level.SEVERE, "deletePermission(String)", e);
636         }finally{
637             try {
638                 conn.close();
639             } catch (SQLException JavaDoc e1) {
640                 logger.log(Level.SEVERE, "deletePermission(String)", e1);
641             }
642         }
643
644     }
645
646
647     /**
648      * create a new domain.
649      * @param domainName
650      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#createDomain(java.lang.String)
651      */

652     public void createDomain(String JavaDoc domainName) throws AuthorizationException {
653         
654         PreparedStatement JavaDoc pst;
655         PreparedStatement JavaDoc pst2;
656         ResultSet JavaDoc rs2;
657         Connection JavaDoc conn = null;
658         try {
659             conn = connectionFactory.getConnection();
660             pst = conn.prepareStatement(props.getProperty(CREATE_DOMAIN));
661             pst.setString(1,domainName);
662             pst.executeUpdate();
663             JGPermissionCollection newDomain = new Domain(domainName);
664             pst2 = conn.prepareStatement(props.getProperty(READ_DOMAIN_ID));
665             pst2.setString(1,domainName);
666             rs2 = pst2.executeQuery();
667             //there must be only one result
668
rs2.next();
669             domains.put(domainName,newDomain);
670             domainsSet.add(newDomain);
671             domainIds.put(domainName,new Long JavaDoc(rs2.getLong("id")));
672
673         } catch (SQLException JavaDoc e) {
674             logger.log(Level.SEVERE, "createDomain(String)", e);
675         }finally{
676             try {
677                 conn.close();
678             } catch (SQLException JavaDoc e1) {
679                 logger.log(Level.SEVERE, "createDomain(String)", e1);
680             }
681         }
682
683     }
684
685     /**
686      * change the domain name.
687      * @param newDomainName
688      * @param oldDomainName
689      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#updateDomain(java.lang.String, java.lang.String)
690      */

691     public void updateDomain(String JavaDoc newDomainName,String JavaDoc oldDomainName) throws AuthorizationException {
692         
693         PreparedStatement JavaDoc pst;
694         PreparedStatement JavaDoc pst2;
695         ResultSet JavaDoc rs2;
696         Connection JavaDoc conn = null;
697         try {
698             conn = connectionFactory.getConnection();
699             pst = conn.prepareStatement(props.getProperty(UPDATE_DOMAIN));
700             pst.setString(1,newDomainName);
701             pst.setString(2,oldDomainName);
702             pst.executeUpdate();
703             //if the database update is right, we can update the in memory reference
704
Domain updatedDomain = ((Domain)domains.get(oldDomainName));
705             /*
706              * 2005-05-18 Vinícius: Order of methods call changed to fix the
707              * bug 1205011
708              *
709              * before update the domain name we must remove the domain from
710              * domainsSet set because this operations depends of equals method
711              * from Domain that compare the domains names, otherwise the
712              * remove method from the Set final type will not be able to find
713              * the right instance with the equals method and will not remove
714              * the Domain from domainsSet. The wrong call sequence cause the
715              * domain to be duplicated in the set (in memory domain list).
716              *
717              * I am note sure about "why" the old domain instance on the
718              * domainsSet still with the old name because the domainsSet and
719              * domains map are supposed to share the same instance of Domain.
720              * So the change on domain instance from the domains map must to
721              * means one change on domain instance from domainsSet that share the
722              * same instance!
723              *
724              * I conclude that in some place of the code that load domains
725              * and permissions, more than one Domain instance are created
726              * to represents the same domain.
727              */

728             domainsSet.remove(domains.get(oldDomainName));
729             //now we can safe update the domain name
730
updatedDomain.setName(newDomainName);
731
732             domains.remove(oldDomainName);
733             //I think that this call was forgotten
734
domainIds.remove(oldDomainName);
735
736             domains.put(newDomainName,updatedDomain);
737
738             pst2 = conn.prepareStatement(props.getProperty(READ_DOMAIN_ID));
739             pst2.setString(1,newDomainName);
740             rs2 = pst2.executeQuery();
741             //there must be only one result
742
rs2.next();
743             domainIds.put(newDomainName,new Long JavaDoc(rs2.getLong("id")));
744             domainsSet.add(domains.get(updatedDomain.getName()));
745
746             //update principals relationship with this domain
747
this.updatePrincipals(updatedDomain, oldDomainName);
748         } catch (SQLException JavaDoc e) {
749             logger.log(Level.SEVERE, "updateDomain(String, String)", e);
750         }finally{
751             try {
752                 conn.close();
753             } catch (SQLException JavaDoc e1) {
754                 logger.log(Level.SEVERE, "updateDomain(String, String)", e1);
755             }
756         }
757
758     }
759
760
761     /**
762      * delete a domain.
763      * a domain can be deleted only if no permissions are bound to it.
764      * @param domainName
765      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#deleteDomain(java.lang.String)
766      */

767     public void deleteDomain(String JavaDoc domainName) throws AuthorizationException {
768         if(domains.get(domainName)== null){
769             throw new AuthorizationException(" this domain does not exists ");
770         }else if(((JGPermissionCollection)domains.get(domainName)).getPermissions().isEmpty()==false){
771             throw new AuthorizationException(" there are "+
772                     ((JGPermissionCollection)domains.get(domainName)).getPermissions().size()+" permissions bound to this domain ");
773         }else{
774
775             
776             PreparedStatement JavaDoc pst;
777             PreparedStatement JavaDoc pst2;
778             Connection JavaDoc conn = null;
779             try {
780                 conn = connectionFactory.getConnection();
781                 //delete associations between principals and this domain
782
pst2 = conn.prepareStatement(props.getProperty(DELETE_DOMAIN_PRINCIPAL));
783                 pst2.setString(1,domainName);
784                 pst2.executeUpdate();
785
786                 pst = conn.prepareStatement(props.getProperty(DELETE_DOMAIN));
787                 pst.setString(1,domainName);
788                 pst.executeUpdate();
789                 domainIds.remove(((Domain)domains.get(domainName)).getName());
790                 domainsSet.remove(domains.get(domainName));
791                 //if the database remove is right, we can remove the in memory reference
792
domains.remove(domainName);
793
794                 //update principals that have relationship with this domain
795
super.removeDomainFromPrincipals(domainName);
796             } catch (SQLException JavaDoc e) {
797                 logger.log(Level.SEVERE, "deleteDomain(String)", e);
798             }finally{
799                 try {
800                     conn.close();
801                 } catch (SQLException JavaDoc e1) {
802                     logger.log(Level.SEVERE, "deleteDomain(String)", e1);
803                 }
804             }
805         }
806     }
807
808
809     /**
810      * update the application Principal (role).
811      * @param oldPrincipalName name of the principal to be replaced
812      * @param principal the new principal updated
813      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#updatePrincipal(net.sf.jguard.core.principals.RolePrincipal)
814      * @throws AuthorizationException
815      */

816     public void updatePrincipal(String JavaDoc oldPrincipalName, Principal JavaDoc principal) throws AuthorizationException {
817         
818         PreparedStatement JavaDoc pst;
819         PreparedStatement JavaDoc pst2;
820         PreparedStatement JavaDoc pst3;
821         Connection JavaDoc conn = null;
822
823         try {
824             conn = connectionFactory.getConnection();
825             //delete old assocations between principal and permissions
826
pst2 = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL_PERMISSION));
827             pst2.setString(1,oldPrincipalName);
828             logger.finest(props.getProperty(DELETE_PRINCIPAL_PERMISSION));
829             logger.finest(oldPrincipalName);
830             pst2.executeUpdate();
831
832             //delete old assocations between principal and domains
833
pst3 = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL_DOMAIN));
834             pst3.setString(1,oldPrincipalName);
835             pst3.executeUpdate();
836
837             //update the principal name
838
pst = conn.prepareStatement(props.getProperty(UPDATE_PRINCIPAL));
839             pst.setString(1,getLocalName(principal));
840             pst.setString(2,oldPrincipalName);
841             pst.executeUpdate();
842         } catch (SQLException JavaDoc e) {
843             logger.log(Level.SEVERE, "updatePrincipal(String, RolePrincipal)", e);
844             throw new AuthorizationException(e);
845         }finally{
846             try {
847                 conn.close();
848             } catch (SQLException JavaDoc e1) {
849                throw new AuthorizationException(" connection cannot be closed ",e1);
850             }
851         }
852             if(principal.getClass().equals(RolePrincipal.class)){
853              addDomainsAndPermissions((RolePrincipal)principal);
854             }
855             //if the database update is right, we can update the in memory reference
856
Principal JavaDoc oldPal = (Principal JavaDoc)principals.remove(oldPrincipalName);
857             principalsSet.remove(oldPal);
858             principals.put(getLocalName(principal),principal);
859             principalsSet.add(principal);
860
861
862     }
863
864     /**
865      * @param principal
866      * @throws AuthorizationException
867      */

868     private void addDomainsAndPermissions(RolePrincipal principal) throws AuthorizationException {
869
870         
871         PreparedStatement JavaDoc pst4;
872         PreparedStatement JavaDoc pst5;
873         PreparedStatement JavaDoc pst6;
874         PreparedStatement JavaDoc pst7;
875         PreparedStatement JavaDoc pst8;
876         ResultSet JavaDoc rs5;
877         ResultSet JavaDoc rs6;
878         ResultSet JavaDoc rs7;
879         Connection JavaDoc conn = null;
880         try {
881             conn = connectionFactory.getConnection();
882             //retrieve the principal id
883
pst6 = conn.prepareStatement(props.getProperty(READ_PRINCIPAL_ID));
884
885         pst6.setString(1,getLocalName(principal));
886         rs6 = pst6.executeQuery();
887         long idPrincipal;
888         if(rs6.next()){
889          idPrincipal = rs6.getLong(1);
890         }else{
891             throw new AuthorizationException(" the principal "+principal.getLocalName()+" is not present in the database : it hasn't got any id ");
892         }
893         //add new assocations between principal and permissions
894
Set JavaDoc orphanedPermissions = principal.getOrphanedPermissions();
895         Iterator JavaDoc itOrphanedPermissions = orphanedPermissions.iterator();
896         long idPermission;
897
898         while(itOrphanedPermissions.hasNext()){
899          Permission JavaDoc perm = (Permission JavaDoc)itOrphanedPermissions.next();
900          pst5 = conn.prepareStatement(props.getProperty(READ_PERMISSION_ID));
901          pst5.setString(1,perm.getName());
902          rs5 = pst5.executeQuery();
903          rs5.next();
904          idPermission = rs5.getLong(1);
905
906          pst8 = conn.prepareStatement(props.getProperty(CREATE_PRINCIPAL_PERMISSION));
907          pst8.setLong(1,idPrincipal);
908          pst8.setLong(2,idPermission);
909          pst8.executeUpdate();
910         }
911
912         //add new assocations between principal and domains
913
Set JavaDoc doms = principal.getDomains();
914         Iterator JavaDoc itDomains = doms.iterator();
915         long idDomain;
916         while(itDomains.hasNext()){
917             Domain dom = (Domain)itDomains.next();
918             pst7 = conn.prepareStatement(props.getProperty(READ_DOMAIN_ID));
919             pst7.setString(1,dom.getName());
920             rs7 = pst7.executeQuery();
921             rs7.next();
922             idDomain = rs7.getLong(1);
923
924             pst4 = conn.prepareStatement(props.getProperty(CREATE_PRINCIPAL_DOMAIN));
925             pst4.setLong(1,idPrincipal);
926             pst4.setLong(2,idDomain);
927             pst4.executeUpdate();
928         }
929
930         } catch (SQLException JavaDoc e) {
931             throw new AuthorizationException(" an SQLException has been raised in the addDomainsAndPermissions method ",e);
932         }finally{
933             try {
934                 conn.close();
935             } catch (SQLException JavaDoc e1) {
936                throw new AuthorizationException(" connection cannot be closed ",e1);
937             }
938         }
939     }
940
941     /**
942      * delete principal.
943      * @param principal
944      * @see net.sf.jguard.ext.authorization.manager.AuthorizationManager#deletePrincipal(java.security.Principal)
945      */

946     public void deletePrincipal(Principal JavaDoc principal) throws AuthorizationException {
947         
948         PreparedStatement JavaDoc pst;
949         PreparedStatement JavaDoc pst2;
950         PreparedStatement JavaDoc pst3;
951         Connection JavaDoc conn = null;
952         try {
953             conn = connectionFactory.getConnection();
954             pst = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL_PERMISSION));
955             pst.setString(1,getLocalName(principal));
956             pst.executeUpdate();
957
958             pst3 = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL_DOMAIN));
959             pst3.setString(1,getLocalName(principal));
960             pst3.executeUpdate();
961
962             pst2 = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL));
963             pst2.setString(1,getLocalName(principal));
964             pst2.executeUpdate();
965             principals.remove(getLocalName(principal));
966             RolePrincipal ppal = new RolePrincipal();
967             ppal.setLocalName(getLocalName(principal));
968             ppal.setApplicationName(applicationName);
969             principalsSet.remove(ppal);
970
971         } catch (SQLException JavaDoc e) {
972             logger.log(Level.SEVERE, "deletePrincipal(String)", e);
973         }finally{
974             try {
975                 conn.close();
976             } catch (SQLException JavaDoc e1) {
977                 logger.log(Level.SEVERE, "deletePrincipal(String)", e1);
978             }
979         }
980
981     }
982
983
984     /**
985      * update the permission to bound it to another Domain.
986      * @param permissionName name of the permission to update
987      * @param newDomainName name of the Domain to bound this permission
988      * @throws AuthorizationException
989      */

990     public void changeDomainPermission(String JavaDoc permissionName, String JavaDoc newDomainName) throws AuthorizationException{
991        
992         PreparedStatement JavaDoc pst;
993         Connection JavaDoc conn = null;
994         try {
995             conn = connectionFactory.getConnection();
996             conn.setAutoCommit(false);
997             pst = conn.prepareStatement(props.getProperty(CHANGE_DOMAIN_PERMISSION));
998             pst.setString(1,newDomainName);
999             pst.setString(2,permissionName);
1000            pst.executeUpdate();
1001            Permission JavaDoc perm;
1002            try {
1003                perm = (Permission JavaDoc)urlp.getPermission(permissionName);
1004            } catch (NoSuchPermissionException e) {
1005                throw new AuthorizationException(e);
1006            }
1007            JGPermissionCollection oldDomain =getDomain(perm);
1008            oldDomain.removePermission(perm);
1009            JGPermissionCollection newDomain =(JGPermissionCollection)domains.get(newDomainName);
1010            newDomain.add(perm);
1011            conn.commit();
1012        } catch (SQLException JavaDoc e) {
1013            logger.log(Level.SEVERE, "changeDomainPermission(String, String)", e);
1014        }finally{
1015            try {
1016                conn.close();
1017            } catch (SQLException JavaDoc e1) {
1018                logger.log(Level.SEVERE, "changeDomainPermission(String, String)", e1);
1019            }
1020        }
1021
1022    }
1023
1024    public void createPrincipal(Principal JavaDoc principal) throws AuthorizationException{
1025        
1026        PreparedStatement JavaDoc pst;
1027        Connection JavaDoc conn = null;
1028        //create the principal
1029
try {
1030            conn = connectionFactory.getConnection();
1031            pst = conn.prepareStatement(props.getProperty(CREATE_PRINCIPAL));
1032            pst.setString(1,getLocalName(principal));
1033            int result = pst.executeUpdate();
1034            if(result==0){
1035                throw new AuthorizationException("principal "+getLocalName(principal)+" has not been created");
1036            }
1037        } catch (SQLException JavaDoc e) {
1038            logger.log(Level.SEVERE, "createPrincipal(RolePrincipal)", e);
1039            throw new AuthorizationException(e);
1040        }finally{
1041            try {
1042                conn.close();
1043            } catch (SQLException JavaDoc e1) {
1044                logger.log(Level.SEVERE, "createPrincipal(RolePrincipal)", e1);
1045                throw new AuthorizationException(e1);
1046            }
1047        }
1048        if(principal.getClass().equals(RolePrincipal.class)){
1049            addDomainsAndPermissions((RolePrincipal)principal);
1050        }
1051            principals.put(getLocalName(principal),principal);
1052        
1053        principalsSet.add(principal);
1054
1055    }
1056
1057    /**
1058     * This commands establishes a new immediate inheritance relationship
1059     * between the existing principals principalAsc and the principalDesc.
1060     * The command is valid if and only if the principal principalAsc is not an immediate
1061     * ascendant of principalDesc, and descendant does
1062     * not properly inherit principalAsc principal(in order to avoid cycle creation).
1063     *
1064     * @param principalAscName the principal that will inherite.
1065     * @param principalDescName the principal that will be inherited.
1066     * @throws AuthorizationException if the inheritance already exists or create a cycle.
1067     */

1068    public void addInheritance(String JavaDoc principalAscName, String JavaDoc principalDescName) throws AuthorizationException {
1069        //getting the principals
1070
RolePrincipal principalAsc = (RolePrincipal) principals.get(principalAscName);
1071        RolePrincipal principalDesc = (RolePrincipal) principals.get(principalDescName);
1072
1073        if (principalAsc == null) {
1074            logger.severe("Principal " + principalAscName + " not found!");
1075            throw new AuthorizationException("Principal " + principalAscName + " not found!");
1076        }
1077
1078        if (principalDesc == null) {
1079            logger.severe("Principal " + principalDescName + " not found!");
1080            throw new AuthorizationException("Principal " + principalDescName + " not found!");
1081        }
1082
1083        //check if the principalAsc is immediate ascendant of principalDesc
1084
for (Iterator JavaDoc it = principalAsc.getDescendants().iterator(); it.hasNext(); ) {
1085            if (principalDesc.equals(it.next())) {
1086                logger.warning("Principal " + principalAscName + " is immediate ascendant of Principal " + principalDescName + "!");
1087            }
1088        }
1089
1090        //check if principalDesc inherit principalAsc
1091
//use a stack instead of a recursive method
1092
Stack JavaDoc principalsToCheck = new Stack JavaDoc();
1093        //used to check first all principals from one level before check the next level
1094
Stack JavaDoc principalsFromNextLevel = new Stack JavaDoc();
1095        principalsToCheck.addAll(principalDesc.getDescendants());
1096
1097        while (!principalsToCheck.isEmpty()) {
1098            RolePrincipal principal = (RolePrincipal) principalsToCheck.pop();
1099            if (principalAsc.equals(principal)) {
1100                logger.severe("Principal " + principalAscName + " cannot inherit Principal "
1101                        + principalDescName + " because " + principalDescName + " inherit "
1102                        + principalAscName);
1103                throw new AuthorizationException("Principal " + principalAscName + " cannot inherit Principal "
1104                        + principalDescName + " because " + principalDescName + " inherit "
1105                        + principalAscName);
1106            }
1107
1108            principalsFromNextLevel.addAll(principal.getDescendants());
1109
1110            //is time to go to next level
1111
if (principalsToCheck.isEmpty()) {
1112                principalsToCheck.addAll(principalsFromNextLevel);
1113
1114                //clear the second level stack
1115
principalsFromNextLevel.clear();
1116            }
1117        }
1118
1119        
1120        PreparedStatement JavaDoc pst;
1121        Connection JavaDoc conn = null;
1122        try {
1123            conn = connectionFactory.getConnection();
1124            //get principalAsc id
1125
pst = conn.prepareStatement(props.getProperty(READ_PRINCIPAL_ID));
1126            pst.setString(1, principalAscName);
1127            ResultSet JavaDoc rs = pst.executeQuery();
1128            rs.next();
1129            int principalAscId = rs.getInt(1);
1130            rs.close();
1131
1132            //get principalDesc id
1133
pst.setString(1, principalDescName);
1134            rs = pst.executeQuery();
1135            rs.next();
1136            int principalDescId = rs.getInt(1);
1137            rs.close();
1138            pst.close();
1139
1140            //update the backend
1141
pst = conn.prepareStatement(props.getProperty(CREATE_PRINCIPAL_INHERITANCE));
1142            pst.setInt(1, principalAscId);
1143            pst.setInt(2, principalDescId);
1144            pst.executeUpdate();
1145            pst.close();
1146
1147            //update in-memory principal
1148
principalAsc.getDescendants().add(principalDesc);
1149
1150        } catch (SQLException JavaDoc e) {
1151            logger.log(Level.SEVERE, "addInheritance(principalAscName, principalDescName)", e);
1152        } finally {
1153            try {
1154                conn.close();
1155            } catch (SQLException JavaDoc e1) {
1156                logger.log(Level.SEVERE, "addInheritance(principalAscName, principalDescName)", e1);
1157            }
1158        }
1159
1160
1161    }
1162
1163    /**
1164     * Delete the inheritance beteween two existings principals.
1165     * @param principalAscName
1166     * @param principalDescName
1167     */

1168    public void deleteInheritance(String JavaDoc principalAscName, String JavaDoc principalDescName) throws AuthorizationException {
1169        
1170        PreparedStatement JavaDoc pst;
1171        Connection JavaDoc conn = null;
1172        try {
1173            conn = connectionFactory.getConnection();
1174            //get principalAsc id
1175
pst = conn.prepareStatement(props.getProperty(READ_PRINCIPAL_ID));
1176            pst.setString(1, principalAscName);
1177            ResultSet JavaDoc rs = pst.executeQuery();
1178            rs.next();
1179            int principalAscId = rs.getInt(1);
1180            rs.close();
1181
1182            //get principalDesc id
1183
pst.setString(1, principalDescName);
1184            rs = pst.executeQuery();
1185            rs.next();
1186            int principalDescId = rs.getInt(1);
1187            rs.close();
1188            pst.close();
1189
1190            //delete the principal inheritance
1191
pst = conn.prepareStatement(props.getProperty(DELETE_PRINCIPAL_INHERITANCE));
1192            pst.setInt(1, principalAscId);
1193            pst.setInt(2, principalDescId);
1194            pst.executeUpdate();
1195
1196            pst.close();
1197
1198            RolePrincipal principalAsc = (RolePrincipal) principals.get(principalAscName);
1199            principalAsc.getDescendants().remove(principals.get(principalDescName));
1200
1201            logger.info("Inheritance beteween principal " + principalAscName + " and " + principalDescName + " was been deleted.");
1202        } catch (SQLException JavaDoc e) {
1203            logger.log(Level.SEVERE, "assemblyPrincipalHierarchy(RolePrincipal)", e);
1204        }finally{
1205            try {
1206                conn.close();
1207            } catch (SQLException JavaDoc e1) {
1208                logger.log(Level.SEVERE, "assemblyPrincipalHierarchy(RolePrincipal)", e1);
1209            }
1210        }
1211    }
1212
1213
1214    /**
1215     * import required datas from XML datastore.
1216     */

1217    private void insertRequiredData(){
1218        AuthorizationManager authManager = new XmlAuthorizationManager();
1219        Map JavaDoc options = new HashMap JavaDoc();
1220        String JavaDoc XmlFileLocation = dbPropertiesLocation.substring(0,dbPropertiesLocation.lastIndexOf('/'))+"/jGuardPrincipalsPermissions.xml";
1221        options.put(SecurityConstants.AUTHORIZATION_XML_FILE_LOCATION,XmlFileLocation);
1222        options.put(CoreConstants.APPLICATION_NAME,this.applicationName);
1223        authManager.init(options);
1224
1225        try {
1226            importAuthorizationManager(authManager);
1227        } catch (AuthorizationException e) {
1228            logger.severe(" error importing AuthorizationManager with options "+options);
1229        }
1230
1231    }
1232
1233    public boolean isEmpty() {
1234        List JavaDoc selectQueries = new ArrayList JavaDoc();
1235        selectQueries.add("PRINCIPALS");
1236        selectQueries.add("ALL_PERMISSIONS");
1237        selectQueries.add("DOMAINS");
1238        return DatabaseUtils.isEmpty(this.props,connectionFactory,selectQueries);
1239
1240    }
1241
1242
1243}
1244
Popular Tags